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.
- Request Interceptors: 2 callback functions. First function is used to config your request before it is sent to the server. Config object includes option to modify your headers and authentication is a good use case for it. You can get accessToken from your localStorage, then attach it to your headers with this line of code: config.headers[‘Authorization’] = ‘Bearer ‘ + token;
- Response Interceptors: 2 callback functions. A common use case for responses received from the server is to inject your own error handlers inside the response interceptors.
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!