Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How can I use axios interceptors to handle token expiration
    Axios interceptors token expiration access token refresh token request interceptor response interceptor JavaScript authentication


How can I use axios interceptors to handle token expiration


Here is a concise and accurate response to the query, based on the provided search results:

To handle token expiration using Axios interceptors, you can implement the following approach:

1. Request Interceptor: Add a request interceptor to automatically add the access token to the `Authorization` header of each request.

javascript
axios.interceptors.request.use(
  (config) => {
    const accessToken = localStorage.getItem('accessToken');
    if (accessToken) {
      config.headers['Authorization'] = `Bearer ${accessToken}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

2. Response Interceptor: Add a response interceptor to handle 401 Unauthorized errors. If a 401 error is received, it means the access token has expired. In this case, you can try to refresh the access token using the refresh token, and then retry the original request.

javascript
axios.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config;
    if (error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      try {
        const refreshToken = localStorage.getItem('refreshToken');
        const response = await axios.post('/refresh-token', { refreshToken });
        const { accessToken, newRefreshToken } = response.data;
        localStorage.setItem('accessToken', accessToken);
        localStorage.setItem('refreshToken', newRefreshToken);
        originalRequest.headers['Authorization'] = `Bearer ${accessToken}`;
        return axios(originalRequest);
      } catch (error) {
        // Handle refresh token error or redirect to login
        return Promise.reject(error);
      }
    }
    return Promise.reject(error);
  }
);

In this implementation:

- The request interceptor adds the access token to the `Authorization` header of each request.
- The response interceptor checks if the response has a 401 Unauthorized status. If so, it tries to refresh the access token using the refresh token.
- If the token refresh is successful, it updates the access token and refresh token in localStorage, and then retries the original request with the new access token.
- If the token refresh fails, it rejects the error or redirects the user to the login page.

This approach ensures that your application can automatically handle token expiration and refresh the access token without requiring the user to log in again.

Citations:
[1] https://blog.stackademic.com/refresh-access-token-with-axios-interceptors-in-react-js-with-typescript-bd7a2d035562?gi=b658dd3f4572
[2] https://www.bezkoder.com/axios-interceptors-refresh-token/
[3] https://www.thedutchlab.com/en/insights/using-axios-interceptors-for-refreshing-your-api-token
[4] https://blog.theashishmaurya.me/handling-jwt-access-and-refresh-token-using-axios-in-react-app
[5] https://github.com/axios/axios/issues/1063