Skip to main content

Command Palette

Search for a command to run...

Axios Interceptors Explained: Middleware for Your Frontend

Published
2 min read
Axios Interceptors Explained: Middleware for Your Frontend
D

Fullstack Developer || MERN Stack

When I first started building login and signup flows in React, one thing confused me a lot:
How do I automatically send tokens with every request and refresh them when expired?

That’s where Axios Interceptors come in.


What is an Interceptor?

An Interceptor is like a middleware in Express.js, but it works on the frontend.

  • In Express, middleware runs before or after a request hits the server.

  • In Axios, an interceptor runs before or after an HTTP request is made from the frontend.

So basically, it sits between your frontend and backend, allowing you to:

  • Attach access tokens to requests

  • Retry failed requests when the token expires

  • Handle errors globally instead of repeating code everywhere


Types of Axios Interceptors

1. Request Interceptor

This runs before sending the request. It is usually used for attaching tokens or modifying headers.

api.interceptors.request.use((config) => {
  const token = localStorage.getItem("accessToken");
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

Explanation:

  • Before the request goes out, Axios checks if you have an accessToken.

  • If yes, it automatically attaches it in the Authorization header.

  • Now you don’t need to manually add a token in every API call.


2. Response Interceptor

This runs after the response comes back. It is used for checking expired tokens and handling errors.

api.interceptors.response.use(
  (response) => response,
  async (error) => {
    if (error.response?.status === 401) {
      console.log("Access Token expired. Refreshing...");
      // call refresh API here
    }
    return Promise.reject(error);
  }
);

Explanation:

  • If the backend sends 401 Unauthorized, Axios catches it.

  • Instead of throwing the error directly, you can:

    • Call the refresh token API

    • Get a new access token

    • Retry the original request with the new token


Why Use Interceptors?

Imagine you have many API calls in your React app. Do you want to:

  • Add tokens manually in every single request?

  • Write the same error handling again and again?

That would make the code repetitive and hard to manage.

Interceptors solve this problem by allowing you to write the logic once and apply it globally.


Final Thought

Think of Axios Interceptors as security guards:

  • The Request Interceptor checks your token before you send the request.

  • The Response Interceptor helps you get a new token if the old one has expired.

So next time you are working with JWT authentication in React, remember:
Interceptor = Middleware for your frontend.