Last active
August 26, 2024 00:24
-
-
Save ModPhoenix/f1070f1696faeae52edf6ee616d0c1eb to your computer and use it in GitHub Desktop.
Axios interceptors token refresh for few async requests. ES6
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
import axios from "axios"; | |
import { settings } from "../settings"; | |
import { authAPI } from "."; | |
const request = axios.create({ | |
baseURL: settings.apiV1, | |
}); | |
request.interceptors.request.use( | |
(config) => { | |
// Get token and add it to header "Authorization" | |
const token = authAPI.getAccessToken(); | |
if (token) { | |
config.headers.Authorization = token; | |
} | |
return config; | |
}, | |
(error) => Promise.reject(error) | |
); | |
let loop = 0; | |
let isRefreshing = false; | |
let subscribers = []; | |
function subscribeTokenRefresh(cb) { | |
subscribers.push(cb); | |
} | |
function onRrefreshed(token) { | |
subscribers.map((cb) => cb(token)); | |
} | |
request.interceptors.response.use(undefined, (err) => { | |
const { | |
config, | |
response: { status }, | |
} = err; | |
const originalRequest = config; | |
if (status === 401 && loop < 1) { | |
loop++; | |
if (!isRefreshing) { | |
isRefreshing = true; | |
authAPI.refreshToken().then((respaonse) => { | |
const { data } = respaonse; | |
isRefreshing = false; | |
onRrefreshed(data.access_token); | |
authAPI.setAccessToken(data.access_token); | |
authAPI.setRefreshToken(data.refresh_token); | |
subscribers = []; | |
}); | |
} | |
return new Promise((resolve) => { | |
subscribeTokenRefresh((token) => { | |
originalRequest.headers.Authorization = `Bearer ${token}`; | |
resolve(axios(originalRequest)); | |
}); | |
}); | |
} | |
return Promise.reject(err); | |
}); | |
export default request; |
Thank you, it works perfectly with my case. It saves my f*cking ass. :)))
Tks you so much!
Why we store promise
to requestSubscribers
? Can't we just return it diretcly, like return new Promise(resolve => {...
Why we store
promise
torequestSubscribers
? Can't we just return it diretcly, likereturn new Promise(resolve => {...
Hi Herbert 😊,
Sure. I will fix it soon)
Congrats!
Thanks a lot, Saved my day :)
Can't this end up in an infinite loop if the refresh endpoint returns a 401?
How to redirect back to /login after any 401 occurred and clear the tokens? Where to place that logic? Can you help in this regard.Thanks
not working to me
For everyone, I recommended using this library instead https://www.npmjs.com/package/axios-auth-refresh
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍