Logo
Published on

Simplified Guide to Implementing Axios Interceptors in Next.js

Authors
  • Name
    Twitter

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.


Step 1: Install Axios

Begin by installing Axios in your Next.js project. Navigate to your project directory in the terminal and execute

npm install axios

Step 2: Configure Axios Interceptors

Create a new file, say axiosInterceptorInstance.js, to configure Axios and define interceptors:

// axiosInterceptorInstance.js  
  
import axios from 'axios';  
  
const axiosInterceptorInstance = axios.create({  
  baseURL: 'https://your-api-base-url.com/', // 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);  
  }  
);  
  
// Response interceptor  
axiosInterceptorInstance.interceptors.response.use(  
  (response) => {  
    // Modify the response data here  
    return response;  
  },  
  (error) => {  
    // Handle response errors here  
    return Promise.reject(error);  
  }  
);  
  
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.

Step 3: Utilize Axios Interceptors in Components

Now, let’s use axiosInterceptorInstance in our components to make API requests:

// interceptorExample.js  
  
import axiosInstance from '../axios/axiosInterceptorInstance';  
  
function InterceptorExample() {  
  const getData = async () => {  
    try {  
      const response = await axiosInstance.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>Interceptor Example</h1>  
      <button onClick={getData}>Fetch Data</button>  
    </div>  
  );  
}  
  
export default InterceptorExample;

What we did just now,

  • We imported the **axiosInterceptorInstance** we defined earlier
  • Used it to make API requests.

Summary

By integrating axiosInterceptorInstance into our Next.js project, requests from our components will automatically pass through the defined interceptors, allowing for easy modification of requests and responses as needed.

Feel free to adapt this approach to your specific project requirements. Happy coding!


Also, to be notified about my new articles and stories:

Follow me on Medium and GitHub, for connecting quickly.

Subscribe to my YouTube Channel, for educational content on similar topics.

You can also find me on LinkedIn.

Cheers!