DEV Community

Cover image for Axios interceptors For ReactJs
Tajul Islam Rifat
Tajul Islam Rifat

Posted on

Axios interceptors For ReactJs

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.

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., axiosInstance.js) to configure your Axios instance and define your interceptors

import axios from 'axios';
const axiosInstance = axios.create({
  baseURL: 'http://api.example.com', // Replace with your API base URL
});

// Request interceptor
axiosInstance.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
axiosInstance.interceptors.response.use(
  (response) => {
    // Modify the response data here
    return response;
  },
  (error) => {
    // Handle response errors here

    return Promise.reject(error);
  }
);

export default axiosInstance;
Enter fullscreen mode Exit fullscreen mode

In the above code, we create an Axios instance using axios.create and 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. You 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. You can parse, transform, or handle errors in the response.

Now, you can use the axiosInstance in your components to make API requests with the configured interceptors. For example, in your component file (example.js)

import axiosInstance from '../axios/axiosInstance';

function ExamplePage() {
  const fetchData = 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>Example Page</h1>
      <button onClick={fetchData}>Fetch Data</button>
    </div>
  );
}

export default ExamplePage;
Enter fullscreen mode Exit fullscreen mode

In the above code, we import the axiosInstance we defined earlier and use it to make API requests. You can replace /api/data with the appropriate endpoint URL for your API.

By using axiosInstance, the requests made from your project components will automatically go through the defined interceptors, allowing you to modify the requests and responses as needed.

Top comments (0)