How to implement axios interceptors in Next.Js application

What are interceptors ?

Interceptors allow you to modify the request or response before it is sent or received by the server. Interceptors are useful because they allow developers to add custom functionality to requests and responses without modifying the actual code that makes the request.

There are two types of interceptors:

  1. Request Interceptor: — It allows you to write or execute a piece of your code before the request gets sent.
  2. Response Interceptor: — It allows you to write or execute a piece of your code before response reaches the calling end.

We will look into both type of Interceptor in this article.

Install axios in your next.js project.

Open your project directory in the terminal and run the following command.

npm install axios

Create a new file (e.g., axiosInterceptorInstance.js) to configure your axios instance and define your interceptors.

import axios from 'axios';

const axiosInterceptorInstance = axios.create({
  baseURL: 'https://otp.dev/api/', // Replace with your API base URL
});

// Request interceptor
axiosInterceptorInstance.interceptors.request.use(
  (config) => {
    // Modify the request config here (add headers, authentication tokens)
        const accessToken = JSON.parse(localStorage.getItem("token"));

    // If token is present add it to request's Authorization Header
    if (accessToken) {
      if (config.headers) config.headers.token = accessToken;
    }
    return config;
  },
  (error) => {
    // Handle request errors here

    return Promise.reject(error);
  }
);
// End of Request interceptor

// Response interceptor
axiosInterceptorInstance.interceptors.response.use(
  (response) => {
    // Modify the response data here

    return response;
  },
  (error) => {
    // Handle response errors here

    return Promise.reject(error);
  }
);
// End of Response interceptor

export default axiosInterceptorInstance;

What we did just now,

  • We created an axios instance using axios.create()
  • Set the baseURL to your API’s base URL. You can modify this according to your API configuration.
  • The interceptors.request.use() function is used to intercept and modify outgoing requests. We can add headers, authentication tokens, or perform other modifications to the request configuration.
  • The interceptors.response.use() function is used to intercept and modify incoming responses. Wecan parse, transform, or handle errors in the response.

Now, we are ready to use axiosInterceptorInstance in our components to make API requests with the configured interceptors.

For example, in our component file (inceptorExample.js)

import axiosInstance from ‘../axios/axiosInterceptorInstance’;

function inceptorExample() {
  const getData = async () => {
    try {
      const response = await axiosInterceptorInstance.get('/api/data'); // Replace with your API endpoint

      // Handle the response data here
      console.log(response.data);
    } catch (error) {
      // Handle the error here
      console.error(error);
    }
  };

  return (
    <div>
      <h1> Inceptor Example </h1>
      <button onClick={getData}>Fetch Data</button>
    </div>
  );
}

export default inceptorExample;

What we did just now,

  • We imported the axiosInterceptorInstance we defined earlier
  • Used it to make API requests.
  • By using axiosInterceptorInstance, the requests made from our project components will automatically go through the defined interceptors, allowing you to modify the requests and responses as needed.

Also, to be notified about my new articles and stories: Follow me on Medium.

Subscribe to my YouTube Channel for educational content on similar topics

Follow me on Medium and GitHub, for connecting quickly

You can find me on LinkedIn as it’s a professional network for people like me and you.

Cheers !!!!!