Last active
April 11, 2024 07:03
-
-
Save FilipBartos/c2cc4df3dfda49f71360295e4101db2b to your computer and use it in GitHub Desktop.
Axios response interceptor for access token refresh supporting 1 to N async requests
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
let isAlreadyFetchingAccessToken = false | |
let subscribers = [] | |
function onAccessTokenFetched(access_token) { | |
subscribers = subscribers.filter(callback => callback(access_token)) | |
} | |
function addSubscriber(callback) { | |
subscribers.push(callback) | |
} | |
axios.interceptors.response.use(function (response) { | |
return response | |
}, function (error) { | |
const { config, response } = error | |
const originalRequest = config | |
if (response && response.status === 401) { | |
if (!isAlreadyFetchingAccessToken) { | |
isAlreadyFetchingAccessToken = true | |
store.dispatch(fetchAccessToken()).then((access_token) => { | |
isAlreadyFetchingAccessToken = false | |
onAccessTokenFetched(access_token) | |
}) | |
} | |
const retryOriginalRequest = new Promise((resolve) => { | |
addSubscriber(access_token => { | |
originalRequest.headers.Authorization = 'Bearer ' + access_token | |
resolve(axios(originalRequest)) | |
}) | |
}) | |
return retryOriginalRequest | |
} | |
return Promise.reject(error) | |
}) |
const { config, response: { status } } = error
causes error when there is no response
add check for response
const { config, response } = error const originalRequest = config if (response && response.status === 401) {
Thanks! Gist updated
First: Thanks a lot for this fantastic gist! Using it now for 2.5 years as a perfect solution for my VueJS 2 application, I ran into problems now when I upgraded Axios from 0.27.2 to the current version 1.1.3. As I am not a very experienced JavaScript programmer I cannot really say what goes wrong. But from what I can see, something goes wrong with the subscriber-list: Original requests are not executed anymore. Do you have any idea how to solve this? Or maybe you can try it with the newest Axios? Thnx a lot!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
causes error when there is no response
add check for response