Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevebaros/0ee01b2316a290d9b46d3662745d94a5 to your computer and use it in GitHub Desktop.
Save stevebaros/0ee01b2316a290d9b46d3662745d94a5 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)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment