Skip to content

Instantly share code, notes, and snippets.

@fersilva16
Created February 22, 2022 17:25
Show Gist options
  • Save fersilva16/75a3b0138d21eeca2ea59339586cd046 to your computer and use it in GitHub Desktop.
Save fersilva16/75a3b0138d21eeca2ea59339586cd046 to your computer and use it in GitHub Desktop.
Auth interceptor to automatically request for new token when the response returns 401
const api = axios.create({
baseURL: apiBaseURL,
});
api.interceptors.request.use(async (config) => {
if (!getToken()) await auth();
return {
...config,
headers: {
Authorization: `Bearer ${getToken()}`,
},
};
});
api.interceptors.response.use(
(response) => response,
async (error) => {
if (error?.response?.status === 401 && !error?.config?.retry) {
await auth();
// eslint-disable-next-line no-param-reassign
error.config.retry = true;
return api(error.config);
}
return Promise.reject(error);
},
);
export default api;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment