Skip to content

Instantly share code, notes, and snippets.

@SamiAlsubhi
Last active May 18, 2022 03:16
Show Gist options
  • Save SamiAlsubhi/3bf6cc5468f39547d57d2035b93e4f55 to your computer and use it in GitHub Desktop.
Save SamiAlsubhi/3bf6cc5468f39547d57d2035b93e4f55 to your computer and use it in GitHub Desktop.
import axios, {AxiosRequestConfig} from "axios";
import axiosLock from "./axiosLock";
const baseAxios = axios.create();
const attachHeaders = (request: AxiosRequestConfig): AxiosRequestConfig => {
//attach auth headers to requests
const accessToken = localStorage.getItem("accessToken");
if (accessToken) {
request.headers["Authorization"] = `Bearer ${accessToken}`;
}
return request
}
const refreshToken = async () Promise<boolean> =>{
//IMPORTANT here you use a new axios instance or an instance created specifically for auth
//and does not have these interceptors
//refresh token and store the new token in localstorage
//return true of successfull
}
//lock requests
baseAxios.interceptors.request.use(async (request) => {
if (axiosLock.isLocked) {
await axiosLock.waitForUnlock();
}
return attachHeaders(request)
})
//Refresh token interceptors
baseAxios.interceptors.response.use(
(response) => {
return response;
},
async (error) => {
const originalRequest = error.config;
//check if the request was not cancelled
if (axios.isCancel(error)) {
return Promise.reject(error);
}
//check if the status code is 401
if (error.response.status !== 401) {
return Promise.reject(error);
}
//check if axios is locked
if (axiosLock.isLocked) {
await apiLock.waitForUnlock()
return axios(attachHeaders(originalRequest))
}
//try to refresh the access_token
axiosLock.lock()
if (await refreshToken()) {
axiosLock.unlock()
return axios(attachHeaders(originalRequest));
}
axiosLock.unlock()
return Promise.reject(error);
}
)
export default baseAxios
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment