Handle 401 errors in a cleaner way with Axios interceptors
Tags: webdev, javascript, react, programming
Published: 2024-03-22 03:45:47

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.

![illustration for interceptors](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jjh9dbe5ifsjyxm1rwel.png)

You can do a lot of things with interceptors, for example, sending a token alongside your request :

```react
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` :

```react
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` :

```react
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](https://idboussadel.me/articles/handle-401-errors-in-a-cleaner-way-with-axios-interceptors).