Skip to content

Instantly share code, notes, and snippets.

@FilipBartos
Last active April 11, 2024 07:03
Show Gist options
  • Save FilipBartos/c2cc4df3dfda49f71360295e4101db2b to your computer and use it in GitHub Desktop.
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
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)
})
@Rassilion
Copy link

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) {

@FilipBartos
Copy link
Author

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

@mschmidt23
Copy link

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