How To Use Axios Interceptors In ReactJS
Axios interceptors are functions that can be registered to be executed before or after a request is sent or a response is received. They are commonly used when you want to handle something on every request/response and don't want to repeat that code on every single request/response.
When To Use Axios Interceptors?
-
Adding an Authorization token to every request for authentication and authorization.
-
Handling errors globally by redirecting to a login page when a 401 Unauthorized error is received.
-
Logging all requests and responses for debugging or tracking purposes.
Modifying the request data before it is sent, such as stringifying a JavaScript object. -
Modifying the response data before it is returned, such as parsing a JSON string into a JavaScript object.
-
Adding a common header to every request, such as a user-agent or a device-type.
-
Handling network errors, such as displaying a message to the user when the internet connection is lost.
-
Changing the base URL of the API depending on the environment (i.e dev, staging, production)
-
Retry failed requests automatically
-
Showing a loading spinner when a request is being sent and hiding it when the response is received.
Let's Understand With An Example Scenario
A react app using Firebase for login and a Firebase token for verification in backend. Assuming our firebase service is a lib folder.
Let's create a file in the root/src directory as `AxiosConfig.js`
Importing Axios and library for firebase
import axios from 'axios';
import { auth } from "./lib/firebase";
Let's assume all our API URLs starts with `/api` prefix. Read more about setting up a scalable backend with Node.js. Let's declare a base URL
const Axios = axios.create({
baseURL: process.env.BASE_URL
});
In your `.env.local` declare your Base URL. You can have different base URL for your production and local, Offcourse
BASE_URL = /api/
Reading Firebase token from local storage and injecting it in every request
Axios.interceptors.request.use(function (config) {
const token = localStorage.getItem('x-token');
config.headers.Authorization = token ? `Bearer ${token}` : '';
return config;
});
Now intercepting response from the server and logging off user if the server responds with Unauthorized. This can happen in 2 cases. The token expired and for some reason we were not able refresh it or the user is trying something fishy
Axios.interceptors.response.use(response => {
return response;
}, error => {
if (error.response.status === 401) {
auth.signOut().then(() => {
window.localStorage.removeItem('x-token');
}).catch((error) => {
// An error happened.
alert(error.message);
});
}
});
You can handle various cases here. Like 404, 500, etc.
Finally exporting the Axios to use in for requests.
export default Axios;
That's it. All you have to do is import this in the components or services(mobx or for some reason if you are using Sagas 😅 ).
It's always better to handle things in one place.
You can even use state management frameworks for showing error or success popups using toastify to give your application a more polished experience.