Managing HTTP requests and responses is quite challenging in modern web development. Fortunately, Axios is a robust JavaScript library that simplifies this process by offering a clean API. 

Axios is a promise-based HTTP client that features a simple intuitive API for sending HTTP requests and handling responses. Interceptors are a primary feature of Axios, helping users modify HTTP requests and responses quickly. 

This post makes you familiar with Axios interceptors and their roles in web development. So without any further delay, let us get started.

 

What are Axios Interceptors?

Axios interceptors are middleware functions that allow you to intercept requests before the primary application logic handles them. These functions are called before a request is sent and after a response is received. 

They provide a way to control and modify the requests and responses that are sent and received by an application. You can use Axios interceptors to alter requests, manage errors, add headers, and more.

We can divide Axios interceptors into two types:

 

Request Interceptors

These interceptors are executed before a request is sent. They enable you to change the request configuration or add authentication tokens and headers.

 

Response Interceptors

As the name suggests, response interceptors are executed upon receiving a response. They allow you to intercept and handle the response before it gets passed to the calling code. These interceptors are quite useful for managing tasks like data transformation and error handling.

 

How Do Interceptors Improve API Interactions?

Interceptors can enhance your API interactions significantly. You can leverage interceptors in the following ways.

 

Centralize Common Functionality

With Interceptor, you do not need to repeat the same code across multiple API calls. You can encapsulate shared logic in interceptors. It supports code reusability and maintainability.

 

Improved Security

Interceptors help you add authentication headers automatically. Besides this, you can manage token refreshing and implement other security measures.

 

Data Transformation

You can transform request and response data before it reaches your application logic. 

 

Authentication & Authorization

Individuals can also use interceptors to attach authentication tokens to requests. It makes sure that all outgoing requests carry the necessary credentials. If a token expires, the interceptor redirects the user to the login page.

 

Use Cases of Axios Interceptors

Adding Authentication Headers

Axios interceptors let you inject authentication headers impeccably into outgoing requests. This feature is useful for APIs that need authorization tokens or API keys.

 

import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://api.example.com',
});

instance.interceptors.request.use(config => {
  const token = localStorage.getItem('authToken');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

export default instance;

 

Handling Errors 

You can also use interceptors to manage errors uniformly throughout your application. Developers can make an error interceptor to find and handle common error responses from the application programming interface.

 

import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://api.example.com',
});

instance.interceptors.response.use(
  response => response,
  error => {
    if (error.response) {
      if (error.response.status === 401) {
        // Redirect to login page
      } else if (error.response.status === 404) {
        // Redirect to 404 page
      }
    }
  return Promise.reject(error);
  }
);

export default instance;

 

Refreshing Tokens

Interceptors also help in refreshing expired authentication tokens. When an API responds with a 401 status, the interceptor catches this response and sends a request for refreshing the token. 

 

axiosInstance.interceptors.response.use(
  response => response,
  async error => {
    if (error.response.status === 401) {
      const originalRequest = error.config;
      const refreshToken = localStorage.getItem('refreshToken');
      
      try {
        const response = await axios.post('/auth/refresh-token', { token: refreshToken });
        localStorage.setItem('token', response.data.token);
        originalRequest.headers.Authorization = `Bearer ${response.data.token}`;
        return axios(originalRequest);
      } catch (e) {
        console.error('Refresh token failed:', e);
        window.location.href = '/login';
        return Promise.reject(e);
      }
    }
    return Promise.reject(error);
  }
);

  

     

Loading Indicators & Cancellation

Interceptors can take the user experience of your application to the next level. They provide a loading indicator during API requests. Besides this, interceptors let you implement request cancellation to prevent unnecessary network traffic. 

 

import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://api.example.com',
});

let activeRequests = 0;

instance.interceptors.request.use(config => {
  activeRequests++;
  // Show loading indicator

  return config;
});

instance.interceptors.response.use(
  response => {
    activeRequests--;
    if (activeRequests === 0) {
      // Hide loading indicator
    }
    return response;
  },
  error => {
    activeRequests--;
    if (activeRequests === 0) {
      // Hide loading indicator
    }
    return Promise.reject(error);
  }
);

export default instance;

 

Final Words

Interceptors in Axios enable developers to intercept and modify HTTP requests and responses. From handling errors to adding headers to managing token expiry, they help you create an efficient and user-friendly application. 

Using interceptors, web developers can empower their applications to manage network interactions securely and smoothly. 

Axios interceptors can help whether you want to handle a simple request modification or a complex token refresh mechanism. 

So if you are a JavaScript developer working on an application that communicates with APIs, leverage the power of Axios interceptors.

 

Leave details and I will get back to you