Last active
May 13, 2020 08:42
-
-
Save nishanbajracharya/bb7519500072d671eaa5a15818b886bc to your computer and use it in GitHub Desktop.
Axios Interceptor for single request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// DEFINE BASE_URL | |
// DEFINE refreshAccessToken, this should use `refreshInstance` instead of `instance` | |
/* | |
function refreshAccessToken() { | |
return refreshInstance | |
.post('token', { | |
refresToken: localStorage.getItem('refreshToken') | |
}) | |
... | |
} | |
*/ | |
// Main axios instance | |
const instance = axios.create({ | |
baseURL: BASE_URL, | |
}); | |
// Instance for refreshing tokens | |
const refreshInstance = axios.create({ | |
baseURL: BASE_URL, | |
}); | |
// Request Interceptor | |
instance.interceptors.request.use((config) => { | |
config.headers['Authorization'] = `Bearer ${localStorage.getItem( | |
'accessToken' | |
)}`; | |
return config; | |
}); | |
// Response Interceptor | |
instance.interceptors.response.use( | |
(config) => config, | |
async (error) => { | |
if ( | |
error.response && | |
error.response.status === 401 && | |
!error.response.config.__isRetry | |
) { | |
// 401 Unauthorized error, probably because the accessToken has expired. | |
// Refetch access token and retry request with new access token | |
// Attach a `__isRetry` as true key to notify that this request is a second one. | |
error.response.config.__isRetry = true; | |
refreshAccessToken().then((refresh) => { | |
if (refresh && refresh.token) { | |
localStorage.setItem('accessToken', refresh.token); | |
error.response.config.headers[ | |
'Authorization' | |
] = `Bearer ${refresh.token}`; | |
instance.request(error.response.config); | |
} | |
}); | |
return; | |
} | |
return Promise.reject(error); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment