DEV Community

Davies
Davies

Posted on • Originally published at sirdavis.hashnode.dev

How to use Axios interceptors to handle 401 API errors and refresh tokens in typescript.

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:

  1. Import the axios library and create an instance of the axios object:
import axios from 'axios';

const instance = axios.create();
Enter fullscreen mode Exit fullscreen mode
  1. 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);
}
Enter fullscreen mode Exit fullscreen mode
  1. 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);
  }
);
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)