Skip to content
the poor coder

send refresh token in axios interceptor

Poor Man
Published
Reading time
2 min read
On this page

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#

Text

    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#

Text

    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#

Text

    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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC