43 lines
1.0 KiB
TypeScript
43 lines
1.0 KiB
TypeScript
import axios, {
|
|
AxiosError,
|
|
AxiosInstance,
|
|
InternalAxiosRequestConfig,
|
|
} from 'axios';
|
|
import { getAccessToken, handleTokenRefresh } from './utils/tokenRefresh';
|
|
|
|
const AUTH_API_URL = process.env.NEXT_PUBLIC_AUTH_API_URL;
|
|
|
|
export const authApi: AxiosInstance = axios.create({
|
|
baseURL: AUTH_API_URL,
|
|
withCredentials: true,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
});
|
|
|
|
const addToken = (config: InternalAxiosRequestConfig) => {
|
|
if (globalThis.window !== undefined) {
|
|
const token = getAccessToken();
|
|
if (token && config.headers) {
|
|
config.headers.Authorization = `Bearer ${token}`;
|
|
}
|
|
}
|
|
return config;
|
|
};
|
|
|
|
authApi.interceptors.request.use(addToken);
|
|
|
|
const handleResponseError = async (error: AxiosError) => {
|
|
const originalRequest = error.config as InternalAxiosRequestConfig & {
|
|
_retry?: boolean;
|
|
};
|
|
|
|
if (!originalRequest) {
|
|
throw error;
|
|
}
|
|
|
|
return handleTokenRefresh(error, originalRequest, authApi);
|
|
};
|
|
|
|
authApi.interceptors.response.use((response) => response, handleResponseError);
|