So the idea is to use a response interceptor that works after the response is available, but before it is passed down in the code.
It looks for unauthenticated
error, which corresponds to statusCode 401
Keep in mind that this is a pseudo-code and You have to modify some parts like
auth.setToken()
.
const createAxiosResponseInterceptor = () => {
const interceptor = axios.interceptors.response.use(
(response) => response,
(error) => {
// Reject promise if not 401 error
if (error.response.status !== 401) {
return Promise.reject(error);
}
/*
* When response code is 401, try to refresh the token.
* Remove the interceptor so it doesn't loop in case
* token refresh causes the 401 response
*
* Also eject the interceptor to prevent it from working again if the REFRESH request returns 401 too
*/
axios.interceptors.response.eject(interceptor);
return axios({
url: API_REFRESH_URL,
method: "POST",
withCredentials: true,
})
.then((response) => {
auth.setToken(response.data.access_token);
error.response.config.headers["Authorization"] =
"Bearer " + response.data.access_token;
return axios(error.response.config);
})
.catch((error) => {
auth.removeToken();
return Promise.reject(error);
})
.finally(createAxiosResponseInterceptor);
}
);
};
createAxiosResponseInterceptor();
error.response.config
contains all the data about the old request so we can repeat it. Keep in mind that after completing the Refresh request we again apply the interceptor in .finally(create...Interceptor)
For more details please see this question, and official Docs here