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


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(
      (error) => {
        switch (error.response.status) {
          case 401:
          case 403:
          // your processing here
            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";

        <App />
        <ResponseInterceptor />
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

Top comments (1)

alexandermirzoyan profile image
Alex Mirzoyan

Interesting solution 🔥