How to add a custom property to axios config?

Viewed 1766

This interceptor should refresh my tokens if expired.

declare module "axios" {
  export interface AxiosRequestConfig {
    _retry?: boolean;
  }
}
axios.interceptors.response.use(
  (res) => res,
  (error: AxiosError) => {
    const originalRequest = error.config;
    console.log(originalRequest._retry); // always undefined
    if (error?.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      return axios
        .post("/auth/refresh-token", {}, { withCredentials: true })
        .then((res) => {
          if (res.status === 201) {
            return axios(originalRequest);
          }
        })
    }
    return Promise.reject(error);
  }
);

The key point is the _retry property that I added to the request config so it should prevent an infinite loop. but the contrary happened! it creates an infinite loop because _retry always is undefined.

I found some issues on their Github page but I didn't found a solution.

EDIT: Su Yu tried this code with the latest version of axios and It worked. So maybe it's a bug. I created an issue in the axios repo: https://github.com/axios/axios/issues/3920

I have a question: What if the refresh token request also returns a 401 error?

FINAL EDIT: Finally, I solved it. I stock in an infinite loop because the refresh token request returns a 401 error if the refresh token expired. So I changed it to 400 and everything works as expected. I'm gonna slape myself right now!

1 Answers

Which version of axios do you use? It seems that axios fixed the issue on 0.19.2. You can check the pull request Fixing custom config options.

I have tried the latest version(0.21.1) of axios, the custom config works fine.

Related