Skip to content

Commit

Permalink
feat: Add axios interceptor setup (kookmin-sw#83)
Browse files Browse the repository at this point in the history
  • Loading branch information
cjeongmin committed May 16, 2024
1 parent 3c35ec5 commit bee1bc9
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import React from 'react';
import './globals.scss';
import './lib/axios';

import {
AuthProvider,
Expand Down
66 changes: 66 additions & 0 deletions src/app/lib/axios.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
'use client';

import axios, {
type AxiosError,
type AxiosRequestConfig,
type AxiosResponse,
} from 'axios';
import { useRouter } from 'next/navigation';

import { getUserData, postTokenRefresh, useAuthActions } from '@/features/auth';
import { load } from '@/shared/storage';

let isRefreshing = false;

axios.interceptors.response.use(
(response: AxiosResponse) => response,
async (error: AxiosError) => {
const router = useRouter();
const { login, logout, setAuthUserData } = useAuthActions();

const { config, response } = error;
const originalRequest = config as AxiosRequestConfig;

const refreshToken = load<string>({
type: 'local',
key: 'refreshToken',
});

if (
response != null &&
refreshToken != null &&
response.status === 401 &&
!isRefreshing
) {
isRefreshing = true;

return await new Promise((resolve, reject) => {
postTokenRefresh(refreshToken)
.then(({ data }) => {
if (originalRequest.headers != null)
originalRequest.headers.Authorization = `Bearer ${data.accessToken}`;

login(data);
getUserData()
.then(({ data: user }) => {
setAuthUserData(user);
})
.catch(err => {
console.error(err);
});

resolve(axios(originalRequest));
})
.catch(err => {
router.push('/');
logout();
reject(err);
})
.finally(() => {
isRefreshing = false;
});
});
}
return await Promise.reject(error);
},
);

0 comments on commit bee1bc9

Please sign in to comment.