Skip to content

Instantly share code, notes, and snippets.

@culttm
Created October 5, 2017 18:46
Show Gist options
  • Star 50 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save culttm/a8c3ca85032c4b0cc67037425f150c44 to your computer and use it in GitHub Desktop.
Save culttm/a8c3ca85032c4b0cc67037425f150c44 to your computer and use it in GitHub Desktop.
axios interceptors for refresh token
axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
const refreshToken = window.localStorage.getItem('refreshToken');
return axios.post('http://localhost:8000/auth/refresh', { refreshToken })
.then(({data}) => {
window.localStorage.setItem('token', data.token);
window.localStorage.setItem('refreshToken', data.refreshToken);
axios.defaults.headers.common['Authorization'] = 'Bearer ' + data.token;
originalRequest.headers['Authorization'] = 'Bearer ' + data.token;
return axios(originalRequest);
});
}
return Promise.reject(error);
});
@ryan-ds17
Copy link

I have 2 async requests, each of them calls refresh_token api. How can I prevent extra api being called?

@mkjiau
Copy link

mkjiau commented Dec 27, 2017

@poohsen
Copy link

poohsen commented Mar 12, 2018

why put the new token in defaults and originalRequest? won't one of them do?

@cyrielo
Copy link

cyrielo commented Apr 23, 2018

@poohsen the originalRequest is a cached configuration copy of the previous request that contains the expired token. The configuration, in this case the headers part also needs to be updated as it won't use the axios defaults even after it has been set.

@ervikashkumar
Copy link

ervikashkumar commented Jun 12, 2018

I have multiple ajax calls in a page in that case many ajax is getting 401 hence many refresh token calls .@poohsen can we avoid this ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment