Skip to content

Commit

Permalink
feat: add axios interceptor for authorization
Browse files Browse the repository at this point in the history
  • Loading branch information
ooooorobo committed Aug 17, 2024
1 parent bec8cb9 commit 69b0023
Showing 1 changed file with 62 additions and 2 deletions.
64 changes: 62 additions & 2 deletions src/shared/lib/custom_instance.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,70 @@
import axios, { AxiosRequestConfig } from 'axios';
import { refreshToken } from 'src/types';

const instance = axios.create({ baseURL: import.meta.env.VITE_API_BASE_URL });

const getAccessToken = () => localStorage?.getItem('accessToken') ?? null;

instance.interceptors.request.use(
(config) => {
if (!config.headers) return config;

let token = null;

if (!config.url?.includes(`/api/v1/auth/refresh-token`)) {
token = getAccessToken();
}

if (token !== null) {
config.headers.Authorization = `Bearer ${token}`;
}

return config;
},
(error) => {
return Promise.reject(error);
},
);

const getRefreshToken = async () => {
try {
const token = getAccessToken();
if (!token) return null;

const response = await refreshToken({ accessToken: token });

return response.accessToken;
} catch (e) {
return null;
}
};

instance.interceptors.response.use(
(response) => {
return response;
},
async (error) => {
const { config } = error;

if (config.url.includes('refresh-token') || error.response.status !== 401 || config.sent) {
return Promise.reject(error);
}

config.sent = true;
const accessToken = await getRefreshToken();

if (accessToken) {
config.headers.Authorization = accessToken;
}

return axios(config);
},
);

export const customInstance = <T>(config: AxiosRequestConfig, options?: AxiosRequestConfig): Promise<T> => {
const promise = axios({
const promise = instance({
...config,
...options,
baseURL: import.meta.env.VITE_API_BASE_URL,
}).then(({ data }) => data);

return promise;
Expand Down

0 comments on commit 69b0023

Please sign in to comment.