React router v6 how to use `navigate` redirection in axios interceptor

In the pre-RRDv6 world you would create a custom history object, to be exported and imported and passed to a Router, and imported and accessible in external javascript logic, like redux-thunks, axios utilities, etc.

To replicate this in RRDv6 you need to also create a custom router component so it can be passed an external history object. This is because all the higher level RRDv6 routers maintain their own internal history contexts, so we need to duplicate the history instantiation and state part and pass in the props to fit the base Router component’s new API.

import { Router } from "react-router-dom";

const CustomRouter = ({ history, ...props }) => {
  const [state, setState] = useState({
    action: history.action,
    location: history.location
  });

  useLayoutEffect(() => history.listen(setState), [history]);

  return (
    <Router
      {...props}
      location={state.location}
      navigationType={state.action}
      navigator={history}
    />
  );
};

Create the history object you need:

import { createBrowserHistory } from "history";

const history = createBrowserHistory();

export default history;

Import and pass to the new CustomRouter:

import customHistory from '../path/to/history';

...

<CustomRouter history={customHistory}>
  ... app code ...
</CustomRouter>

Import and consume in your axios functions:

import axios from "axios";
import history from '../path/to/history';

export const api = axios.create({
  baseURL: "http://127.0.0.1:8000/",
  headers: {
    "content-type": "application/json",
  },
});

api.interceptors.response.use(
  function (response) {
    return response;
  },
  function (er) {
    if (axios.isAxiosError(er)) {
      if (er.response) {
        if (er.response.status == 401) {
          history.replace("/login"); // <-- navigate
        }
      }
    }

    return Promise.reject(er);
  }
);

Update

react-router-dom now exports a history router, i.e. unstable_HistoryRouter.

Example:

import { unstable_HistoryRouter as HistoryRouter } from "react-router-dom";
import history from '../path/to/history';

...

<HistoryRouter history={customHistory}>
  ... app code ...
</HistoryRouter>

Note:

This API is currently prefixed as unstable_ because you may
unintentionally add two versions of the history library to your app,
the one you have added to your package.json and whatever version React
Router uses internally. If it is allowed by your tooling, it’s
recommended to not add history as a direct dependency and instead rely
on the nested dependency from the react-router package. Once we have a
mechanism to detect mis-matched versions, this API will remove its
unstable_ prefix.

Leave a Comment