skip to Main Content

I want to redirect to '/login' in axios interceptor while handling error.

My code:

import axios from "axios";
import { redirect } from "react-router-dom";

export const instance = axios.create()

instance.interceptors.request.use(
  ... other code
);

instance.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    const originalRequest = error.config;
    console.log(error?.response.data)
    console.log(originalRequest._retry)

    if (
      error.response.status === 401 &&
      originalRequest.url === "http://0.0.0.0:8000/auth/refresh-token"
    ) {
      localStorage.removeItem("refresh_token");
      localStorage.removeItem("access_token");

      // I tried this
      return redirect("/login")

      // And also I tried this
      //router.navigate("/login");
      return Promise.reject(error);
    }

    if (error.response.status === 401 && !originalRequest._retry) {
     ... other code
    }
    return Promise.reject(error);
  }
);

I’ve tried two ways to do this:

  • First: return redirect
  • Second: router.navigate

But nothing works.

This how I defined router:

export const router = createBrowserRouter([
  { path: "*", Component: Root },
]);

2

Answers


  1. I used to implement React routing using useNavigate() in react-router-dom. You can refer below.

    import axios from "axios";
    import { useNavigate } from "react-router-dom";
    
    export const instance = axios.create();
    
    instance.interceptors.request.use(
      ... other code
    );
    
    instance.interceptors.response.use(
      (response) => {
        return response;
      },
    
      (error) => {
        const originalRequest = error.config;
        console.log(error?.response.data)
        console.log(originalRequest._retry)
        const navigate = useNavigate()
    
        if (
          error.response.status === 401 &&
          originalRequest.url === "http://0.0.0.0:8000/auth/refresh-token"
        ) {
          localStorage.removeItem("refresh_token");
          localStorage.removeItem("access_token");
    
          navigate("/login");
          return Promise.reject(error);
        }
    
        if (error.response.status === 401 && !originalRequest._retry) {
         ... other code
        }
        return Promise.reject(error);
      }
    );
    
    Login or Signup to reply.
  2. The redirect utility only works in Route component’s loaders/actions. I suggest importing the axios instance so the interceptors can be instantiated in scope with the useNavigate hook using a useEffect hook. If you like, the logic can be abstracted into a custom hook.

    Example:

    import { useEffect } from 'react';
    import { useNavigate } from 'react-router-dom';
    import { instance as axiosInstance } from '../path/to/axiosInstance';
    
    const useAxiosInterceptors = () => {
      const navigate = useNavigate();
    
      useEffect(() => {
        const requestInterceptor = axiosInstance.interceptors.request.use(
          ... other code
        );
        
        const responseInterceptor = axiosInstance.interceptors.response.use(
          (response) => {
            return response;
          },
          (error) => {
            const originalRequest = error.config;
        
            if (error.response.status === 401) {
              if (originalRequest.url === "http://0.0.0.0:8000/auth/refresh-token") {
                localStorage.removeItem("refresh_token");
                localStorage.removeItem("access_token");
        
                navigate("/login", { replace: true });
                return Promise.reject(error);
              }
        
              if (!originalRequest._retry) {
                ... other code
              }
            }
            return Promise.reject(error);
          }
        );
    
        // Return cleanup function to remove interceptors if necessary
        return () => {
          axiosInstance.interceptors.request.eject(requestInterceptor);
          axiosInstance.interceptors.response.eject(responseInterceptor);
        };
      }, []);
    };
    

    Use the useAxiosInterceptors hook in your route protection component.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search