DEV Community

Davies
Davies

Posted on • Originally published at sirdavis.hashnode.dev

3 1

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay