DEV Community

Cover image for Handle 401 errors in a cleaner way with Axios interceptors
abdessamad idboussadel
abdessamad idboussadel

Posted on

Handle 401 errors in a cleaner way with Axios interceptors

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;


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

and



npm i js-cookie


Enter fullscreen mode Exit fullscreen mode

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;
};


Enter fullscreen mode Exit fullscreen mode

Then we import ResponseInterceptorin 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>
);


Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
alexandermirzoyan profile image
Alex Mirzoyan

Interesting solution 🔥

Collapse
 
asma_a246a0e3 profile image
Asma

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.
Image descriptionThe 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:
Image description

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?