How to use Axios interceptors to handle 401 API errors and refresh tokens in typescript.
A brief overview of how to automatically refresh the access token and retry the original request in a typescript/javascript application
Table of contents
No headings in the article.
To use Axios interceptors to handle 401 API errors and refresh access/JSON web tokens(JWTs) tokens in TypeScript/Javascript, you can do the following:
- Import the
axios
library and create an instance of theaxios
object:
import axios from 'axios';
const instance = axios.create();
- Define a function to refresh the access token using a refresh token:
function refreshAccessToken(refreshToken: string): Promise<string> {
// Send a request to the server to refresh the access token using the refresh token
return axios
.post('/refresh-token', { refreshToken })
.then((response) => response.data.accessToken);
}
- Add an interceptor to the
instance
object to handle 401 errors. In the interceptor, check for a 401 error, and if one is found, refresh the access token using the refresh token and retry the original request:
instance.interceptors.response.use(
(response) => response,
(error) => {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
const refreshToken = // Get the refresh token from storage
return refreshAccessToken(refreshToken).then((accessToken) => {
// Replace the access token in the original request config
originalRequest.headers['Authorization'] = `Bearer ${accessToken}`;
return instance(originalRequest);
});
}
return Promise.reject(error);
}
);
With this in place, whenever an Axios request returns a 401 error, the interceptor will automatically refresh the access token and retry the original request.
It's important to note, however, that this example is just a rough outline of how to use Axios interceptors to handle 401 errors and refresh access tokens in TypeScript. You will need to handle additional edge cases in a real-world application and implement proper error handling.
For more information, be sure to refer to Axios' official documentation on interceptors.