Created
February 22, 2022 17:25
-
-
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
This file contains hidden or 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
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