Using React Router Inside Axios Interceptors

Axios: “Promise based HTTP client for the browser and node.js”

React-router: “React Router is a collection of navigational components that compose declaratively with your application.”


In this article, I will utilize the powerful feature of Axios called Interceptors to intercept requests/responses before they reach the next stages (then() and catch()). I assume you have basic knowledge of Axios, React and React-router before continuing reading since I will abstract the fundamentals away.


How does Interceptors work?


Src: Axios Github page


From picture above, you can see there are two types of interceptors for request and response.

Let’s take a look at this example.

In the main index.js file, I have imported Router from ‘react-router-dom’ to create my custom history. <Router> is a common low-level interface, which suits the purpose of synchronizing history with Redux.



Inside the response interceptors, I want to add toast notifications to the user interface whenever I got error responses from server such as “Network Error” or 500. Axios error message only includes status code by default, which might not be user-friendly in many cases. Another useful scenario is that you might wanna use react-router to route your users to notfound page if server returns 404 or 400 status. It’s a way to make errors more meaningful to you as well as your users.

And that’s how you implement react-router outside a react component!


Contact Person

Blog writer

Nhu Kangasniemi

Bilot Alumni