send refresh token in axios interceptor

How to Send Refresh Token in Axios Interceptor?

If you are building a web application that requires user authentication, chances are you are using JWT (JSON Web Token) to verify the user's identity. JWTs have an expiration time, which means that after a certain period, the token will expire, and the user will need to log in again to get a new token.

To avoid forcing the user to log in again and again, we can use a refresh token. A refresh token is a long-lived token that can be used to get a new access token when the access token has expired. In this PAA, I will explain how to send the refresh token in an Axios interceptor.

Step 1: Set Up Axios Interceptor


    axios.interceptors.request.use(
      async (config) => {
        const token = await getToken();
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
  

The above code sets up an Axios interceptor that intercepts every request before it is sent. It adds the JWT access token to the Authorization header of the request.

Step 2: Add Token Refresh Logic


    let isRefreshing = false;
    let refreshSubscribers = [];
  
    const subscribeTokenRefresh = (cb) => {
      refreshSubscribers.push(cb);
    };
  
    const onTokenRefreshed = () => {
      refreshSubscribers.map((cb) => cb());
    };
  
    axios.interceptors.response.use(
      (response) => {
        return response;
      },
      async (error) => {
        const { config } = error;
  
        if (!isRefreshing) {
          isRefreshing = true;
          const token = await getRefreshToken();
          axios
            .post("/auth/refresh-token", { token })
            .then((response) => {
              setToken(response.data.token);
              isRefreshing = false;
              onTokenRefreshed();
              refreshSubscribers = [];
            })
            .catch((error) => {
              console.log(error);
            });
        }
  
        return new Promise((resolve) => {
          subscribeTokenRefresh(() => {
            config.headers.Authorization = `Bearer ${getToken()}`;
            resolve(axios(config));
          });
        });
      }
    );
  

The above code adds a response interceptor to Axios. It checks if the response is a 401 Unauthorized error. If it is, it sends a request to refresh the token using the refresh token. If the refresh token is valid, it sets the new access token in local storage and calls the onTokenRefreshed function. The function then calls all the callbacks (in this case, there is only one) in the refreshSubscribers array. Finally, it clears the array.

Step 3: Use the Axios Interceptor with Refresh Token


    async function getData() {
      try {
        const response = await axios.get("/api/data");
        console.log(response.data);
      } catch (error) {
        console.log(error);
      }
    }
  

The above code shows an example of using Axios to get data from an API endpoint. When this function is called, the Axios interceptor intercepts the request, adds the JWT access token to the Authorization header, and sends the request. If the access token has expired, the response interceptor intercepts the response, sends a request to refresh the token, gets a new access token using the refresh token, and calls the onTokenRefreshed function.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe