In this article, we will discuss how to use interceptors to intercept your 401 error response or any response for that matter that you want to process. React will be utilized in the provided examples.
Axios interceptors function as middleware permitted by Axios to intercept requests or responses, enabling their processing before they reach their destination.
You can do a lot of things with interceptors, for example, sending a token alongside your request :
import axios from "axios";
import Cookies from "js-cookie";
const api = axios.create({
baseURL: "http://localhost:8000",
withCredentials: true,
withXSRFToken: true,
timeout: 6000,
headers: {
Accept: "application/json",
},
});
api.interceptors.request.use((config) => {
if (Cookies.get("token")) {
config.headers["Authorization"] = "Bearer " + Cookies.get("token");
}
return config;
});
export default api;
You can be creative and utilize interceptors to make your code cleaner and more readable.
Handling 401 errors with interceptors in react
First we install :
npm i axios
and
npm i js-cookie
Then we create a new component ResponseInterceptor
:
import { useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import api from "../services/api";
import Cookies from "js-cookie";
export const ResponseInterceptor = () => {
const navigate = useNavigate();
const interceptorId = useRef(null);
useEffect(() => {
interceptorId.current = api.interceptors.response.use(
undefined,
(error) => {
switch (error.response.status) {
case 401:
Cookies.remove("token");
localStorage.removeItem("userData");
navigate("/");
break;
case 403:
// your processing here
default:
return Promise.reject(error);
}
}
);
}, [navigate]);
return null;
};
Then we import ResponseInterceptor
in the main.jsx
:
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.jsx";
import "./index.css";
import { BrowserRouter as Router } from "react-router-dom";
import { ResponseInterceptor } from "./components/ResponseInterceptor.jsx";
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<Router>
<App />
<ResponseInterceptor />
</Router>
</React.StrictMode>
);
In conclusion, Axios interceptors provide a powerful mechanism for intercepting and manipulating HTTP requests and responses in a flexible and centralized manner.
By utilizing interceptors, developers can implement various functionalities such as error handling, request/response logging, authentication token management, and more.
This approach enhances code modularity, readability, and maintainability by allowing common behaviors to be encapsulated and reused across multiple API calls.
This article was originally published on my website idboussadel.me.
Top comments (2)
Interesting solution 🔥
I'm experiencing a 401 (Unauthorized) error when trying to fetch user data with a token in my React application using Axios. This happens when I attempt to call the getUserByToken function.
The authToken is set correctly in the Redux store, and I'm logging it right before the request. Here’s how I set the token: dispatch(auth.actions.login(token)); I'm using Axios interceptors to attach the token to the headers:
ps: the token is not present in the request headers in my browser’s developer tools (under the "Network" tab)
What could be causing the 401 (Unauthorized) error despite having the token set?
Are there any common issues with token handling in Axios that I should be aware of?