1
votes

We are implementing a token-based authentication and when a user signs in we generate access and refresh tokens then save that with the timestamp on device so we can later check if the access token is expired or not.

We are currently using axios interceptor before every request and checking if the token is still valid or not with the timestamp we saved earlier when we generated the access and refresh tokens, but when the access token is expired and we are making a request to refresh the token the app goes on an infinite loop and none of the requests go through (both the original and refresh token api requests). you can see my code below:

const instance = axios.create({
  baseURL: 'http://localhost:8080'
});

const refreshToken = () => {
  return new Promise((resolve, reject) => {
    instance
      .post('/token/renew')
      .then(response => {
        resolve('refresh successful');
      })
      .catch(error => {
        reject(Error(`refresh fail: ${error}`));
      });
  });
};

instance.interceptors.request.use(
  async config => {
    const timestamp = 1602155221309;
    const diffMinutes = Math.floor(Math.abs(Date.now() - timestamp) / 60000);

    // if diffMinutes is greater than 30 minutes
    if (diffMinutes > 30) {
      const tokenResponse = await refreshToken();
      return config;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
1

1 Answers

1
votes

The infinite loop is caused by your interceptor triggering another Axios request on which said interceptor will also run and trigger another Axios request, forever.

A simple solution would be to make the refresh token network request using the default axios instance which doesn't include any interceptors:

const refreshToken = () => {
  // You can skip returning a new `Promise` since `axios.post` already returns one.
  return axios.post("YOUR_BASE_URL/token/renew");
};

Obviously that also means you'll have to write a bit of logic to send the current refresh token along if that's included in your instance interceptors.