Setup axios – redirect page using react-router-dom in interceptor

Tram Ho


This article solves 2 problems

  1. How to install axios
  2. How to use react-router-dom in axios interceptor to switch pages without having to reload the whole website


Install axios

  • npm: npm install axios
  • yarn: yarn add axios

Switch pages in interceptor using react-router-dom


In reactjs or in any single page app we don’t want to have to re-load the whole page, this makes the browser have to reload all resources (js, css, image, font,..) which reduces the experience. user experience without taking advantage of the power of single page app . To navigate through pages we usually use the useHistory/useNavigate hook of react-router-dom, but the axios interceptor is not a react-component so the hook cannot be used. So they must do?


  • Use another react-router-dom which allows to move the page without hooks
  • Call interceptor inside react-component to use hook

Of course, in this article, I will deal with the second direction, the mindset as follows:

  • How to set interceptor in component?
    • Call the interceptor immediately App.tsx of the project, do not create it only once. So ease!
  • If it can be set, how will the places that need to be used axios be used?
    • In order for other places (components, functions) to be available, it is necessary to share the instance with the axios interceptor in the App.tsx above.


B1: Call interceptor right in the first component App.tsx
Here, for example, if the status is 401, it will redirect to /login

That’s it, the navigation problem is over

B2: How can I reuse axiosInstance because I only have a custom interceptor for it, if I use another instance, it won’t navigate anymore, should I export it from App.tsx???

To bring back the same instance, there are two ways.

  • Method 1: Use singleton pattern
  • Method 2: Reuse the library instance itself

Here I will use method 2, and method 1, you guys will find out more by yourself. You just need to replace axiosInstance with axios imported directly from the library

That’s it, so simple

B3: Fix bug

When you get to this step, you will definitely get an error because you use useNavigate outside of RouterProvider . Then just put this pile of code into RouterProvider . Here I am using react-router-dom 6.8 which may be a bit different from everyone else. But the mindset is to put the interceptor setup inside RouterProvider to use useNavigate or useHistory

How to use


That’s it, hope you understand the article.

Share the news now

Source : Viblo