blog image

Handle 401 errors in a cleaner way with Axios interceptors

Mar 22, 2024

Axios - React - developer - Programming - Webdev

Reading Time: 2 min read

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

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.

linkedin icongithub icontwitter or x icon