Axios Interceptors with Practical Examples

Axios Interceptors with Practical Examples

Axios is the go-to JavaScript library for handling requests to websites.

In this guide, we'll start with the basics of something called 'Axios interceptors.' Think of them as clever tools built into Axios that let you tweak requests and responses without causing any trouble. We'll also explore practical examples so that you can use them in your projects.

What is Axios?

Axios is a popular promise-based JavaScript library for making HTTP requests. Axios provides an easy-to-use API for making different types of requests such as GET, POST, PUT and DELETE. It also supports advanced features such as the cancellation of requests, interceptors, and automatic transformation of request and response data to JSON.

To install and use Axios in your project you can run the following command:

npm install --save axios

What are Axios interceptors?

Axios interceptors are functions that are called before a request is sent and after a response is received. They provide a way to modify and control the requests and responses that are sent and received by the application. Interceptors can be used to add headers, modify requests, handle errors, and much more.

Adding Axios Interceptors

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

Example 1: Adding Authentication Headers

Interceptors can be used to seamlessly inject authentication headers into outgoing requests. This is particularly useful for APIs that require 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;

Example 2: Handling Errors Globally

Interceptors can also help in managing errors uniformly across your application. You can create an error interceptor to catch and handle common error responses from the API.

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;

Example 3: Loading Indicators and Cancellation

Interceptors can help enhance user experience by providing loading indicators during API requests. Additionally, you can implement request cancellation to prevent unnecessary network traffic when users navigate away from a page.

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;

Example 4: Token Expiry and Automatic Refresh

For applications using JWT tokens, interceptors can be used to detect token expiry and automatically refresh the token before making the actual request.

import axios from 'axios';

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

let isRefreshing = false;

instance.interceptors.response.use(
  response => response,
  async error => {
    const originalRequest = error.config;
    if (error.response.status === 401 && !originalRequest._retry) {
      if (!isRefreshing) {
        isRefreshing = true;
        // Refresh token logic here

        // Once the token is refreshed, replay the original request
        originalRequest._retry = true;
        return instance(originalRequest);
      }
    }
    return Promise.reject(error);
  }
);

export default instance;

Removing an Axios interceptor

If we need to remove the request interceptor later on, we will need to instantiate it store it as a constant and just call the eject() function.

const axiosInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(axiosInterceptor);

Conclusion

By exploring these examples of using Axios interceptors, you can see how versatile they can be in various aspects of your API interactions. From adding headers and handling errors to providing loading indicators and handling token expiry, interceptors empower you to create more efficient, resilient, and user-friendly applications.

The flexibility and power of Axios interceptors make them a valuable tool for any JavaScript developer working on web applications that communicate with APIs.