Axios Interceptors in a React application

May 27, 2023, Tags - Axios Javascript React

In this article, we are going to learn how to use Axios Interceptors in a React applications. If you are new to Axios you can learn more about it here - How to perform POST, GET and DELETE request using Axios in React

In short, Axios is a popular JavaScript library used for making HTTP requests from a browser or Node.js. Axios supports various methods like GET, POST, PUT, DELETE, etc., and provides an easy-to-use API for making HTTP requests.

Axios comes with a feature called Interceptors that allows our app to intercept requests. With Axios Interceptors, we can set up functions that will be executed for every request or response before they are handled by the application.

Why we need to use Axios Interceptors

Let's first understand how Axios interceptor works.

When a request is made, the request interceptor is triggered before the request is sent to the server. This interceptor can be used to modify the request headers, attach authentication tokens, or perform any other necessary preprocessing before the request is sent.

Likwise, when a response is received from the server, the response interceptor is triggered. This interceptor allows us to handle the response data, perform error handling, or make any necessary transformations before the response is passed back to the calling code.

Thus, interceptors provide a way to centralize common functionality across multiple requests. This way, we can efficiently handle common request and response logic, enhance security, and streamline API interactions in our application.

For example, if we need to include an authorization token in every request, we can just define a request interceptor that adds the token to the headers automatically. This way we need not to manually add the token to each request separately.

How to use Axios interceptor in React

Let's configure Axios interceptor in a React app. Assuming we already have basic setup and running React.js application, we will follow the 4 step setup.

  1. Install Axios in our React.js project
  2. Create Axios instance and configurations
  3. Register all our API endpoints
  4. Import the API functions and make API request

Step 1: Install Axios in our React.js project

Open the project and run the below command in the root to install the axios -

npm install axios

Step 2: Create Axios instance and configurations

Let's create a file called API.js in our project's src directory. It will contain functions that make the actual HTTP requests using Axios. Here's an basic structure for the API.js file

import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.base-url.com/api', // our API base URL
});

// Request interceptor for adding the bearer token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token'); // Assuming you store the token in localStorage
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);


// Export the api instance
export default api;

 

We simply imported the axios from the package that we installed in step 1. Then we defined the Axios instance with our baseURL for all the API endpoints using axios.create() function.

In next step, assuming we have stored our encrypted token in localStorage, we get the token and send this Bearer Token in the Authorization header to consume our API. Now every time a request is made the bearer token will be automatically sent to header to access protected resources.

At the end, we simply export our instance so that we can call it in our React components to make API calls. But before that, we also need to define our endpoints.

Let's move the step 3.

Step 3: Register API endpoints

While we are in the API.js file, let's add some API endpoints just before exporting our instance.

import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.base-url.com/api', // our API base URL
});

// Request interceptor for adding the bearer token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token'); // Assuming you store the token in localStorage
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);


// API endpoints
export const getUser = () => {
  return api.get('/user');
};

export const deleteUser = (userId) => {
  return api.delete(`/user/${userId}`);
};


// Export the api instance
export default api;

We have added 2 end-points in our API.js file - getUser and, deleteUser. That is all.

So far, we have installed axios library, setup our axios instance and we have added our end points. To make it easy to understand, our end point url for getting user details will be - 

https://api.example.com/api/user

Step 4: Import the API functions and make API request

Now it is time to consume the APIs. Let's create a React component naming UserComponent.jsx that renders -

import { useEffect, useState } from 'react';
import { getUser, deleteUser } from './API';

const UserComponent = () => {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const fetchUser = async () => {
      try {
        const response = await getUser();
        setUser(response.data);
      } catch (error) {
        console.error('Error fetching user:', error);
      }
    };

    fetchUser();
  }, []);

 {/* a function to handle delete user */}
  const handleDeleteUser = async () => {
    try {
      await deleteUser(user.id);
      // Handle success
       console.log('User deleted successfully.')
    } catch (error) {
      console.error('Error deleting user:', error);
    }
  };

  return (
    <div>
      {/* Render user data and button to delete user */}
      {user && (
        <>
          <h2>{user.name}</h2>
          <button onClick={handleDeleteUser}>Delete User</button>
        </>
      )}
    </div>
  );
};

export default UserComponent;

In above example component, we simply import the functions getUser and deleteUser from the API.js file. Then the useEffect hook is used to fetch the user data when the component mounts. Next, we create a function handleDeleteUser and use it with the button. When the button is clicked handleDeleteUser function is triggered and our api request is made. We also have basic handling of errors or success cases.

As the application grows, we keep adding the api end-points in our API.js. This is just a basic configuration to start with. We can modify it further as per our need.



Gautam Kumar

Editor

Leave a comment