Skip to content

Instantly share code, notes, and snippets.

@spokvulcan
Last active March 2, 2025 13:30
Show Gist options
  • Select an option

  • Save spokvulcan/f1070f1696faeae52edf6ee616d0c1eb to your computer and use it in GitHub Desktop.

Select an option

Save spokvulcan/f1070f1696faeae52edf6ee616d0c1eb to your computer and use it in GitHub Desktop.
Axios interceptors token refresh for few async requests. ES6
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;
@exwyezed
Copy link
Copy Markdown

Thanks for sharing this, it helped me a lot. Here's mine btw: https://gist.github.com/alfonmga/96474f6adb6ed8dee8bc8bf8627c0ae1

@Flyrell
Copy link
Copy Markdown

Flyrell commented Nov 23, 2018

Here's a small package I created for this one -> axios-auth-refresh.
I'd be more than glad to get your contributions, as it's pretty simple right now (it'd probably need to react on more status codes, queue the requests while the token obtaining process is running, etc.).

@AndreyPatseiko
Copy link
Copy Markdown

Thanks men you save my day.

@cprebble
Copy link
Copy Markdown

๐Ÿ‘

@khoabk12
Copy link
Copy Markdown

Thank you, it works perfectly with my case. It saves my f*cking ass. :)))

Copy link
Copy Markdown

ghost commented Oct 15, 2019

Tks you so much!

@bertdida
Copy link
Copy Markdown

Why we store promise to requestSubscribers? Can't we just return it diretcly, like return new Promise(resolve => {...

@spokvulcan
Copy link
Copy Markdown
Author

Why we store promise to requestSubscribers? Can't we just return it diretcly, like return new Promise(resolve => {...

Hi Herbert ๐Ÿ˜Š,

Sure. I will fix it soon)

@sergiodanilo
Copy link
Copy Markdown

Congrats!

@developerKumar
Copy link
Copy Markdown

Thanks a lot, Saved my day :)

@EnriqueDev
Copy link
Copy Markdown

EnriqueDev commented Apr 23, 2020

Can't this end up in an infinite loop if the refresh endpoint returns a 401?

@FatehAK
Copy link
Copy Markdown

FatehAK commented May 17, 2020

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

@fukemy
Copy link
Copy Markdown

fukemy commented Nov 17, 2022

not working to me

@spokvulcan
Copy link
Copy Markdown
Author

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