Intercepting Requests and Responses with Axios Interceptors

Axios is a popular package for making HTTP requests in JavaScript applications. It provides a simple and efficient way to communicate with external APIs or your own server. One of the powerful features Axios offers is the ability to intercept requests and responses.

Interceptors allow you to apply middleware-like functions to requests and responses. They enable you to modify a request or response before it is actually sent or received.

If you are new to this concept, in this article, we will explore how to use Axios interceptors with practical examples.

What are Axios Interceptors?

Axios interceptors are functions that can be defined to run before or after an HTTP request is made or after a response is received. These interceptors provide a way to globally handle certain aspects of HTTP requests and responses, such as adding authentication headers, logging requests, or handling errors consistently.

Axios provides two types of interceptors: Request Interceptors and Response Interceptors

Request Interceptors

Request interceptors are functions that are executed right before a request is made. They can be used for various purposes, such as adding authentication headers, logging requests, or modifying request data. To create a request interceptor, you can use the axios.interceptors.request.use method

axios.interceptors.request.use(request => {
  // Modify the request config
  request.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
  return request;
});

In this example, we’re adding an authorization header with a token stored in the local storage to every outgoing request.

Here, the request object includes various properties and settings related to the HTTP request that Axios is about to send

  • url: The URL to which the request is being sent.
  • method: The HTTP method of the request (e.g., GET, POST, PUT, DELETE).
  • headers: An object representing the HTTP headers for the request.
  • params: An object containing query parameters to be included in the request URL for GET requests.
  • data: The request payload for POST or PUT requests, typically in JSON format.
  • auth: An object that can be used to specify authentication credentials for the request.
  • timeout: The maximum time in milliseconds to wait for the request to complete.

Using these properties, you can change the request configuration, add headers, or even cancel the request based on certain conditions.

Response Interceptors

On the other hand, response interceptors are functions that are executed after a response is received but before it’s passed to your application code. They are useful for globally handling common error scenarios, logging responses, or transforming data. To create a response interceptor, you can use the axios.interceptors.response.use method.

axios.interceptors.response.use(response => {
  // Modify the response data
  response.data = response.data.toUpperCase();
  return response;
}, error => {
  // Handle errors
  return Promise.reject(error);
});

In this example, we’re converting the response data to uppercase before it’s used in the application. If an error occurs, we handle it by rejecting the promise.

So, the response object in this context includes the following properties (among others):

  • data: This is the actual response data received from the server before you modified it to uppercase.
  • status: The HTTP status code of the response.
  • statusText: The HTTP status text of the response.
  • headers: The response headers.

By modifying the properties of the responseobject, you are altering the response that will be used by the code that originally made the HTTP request.

Using Interceptors in Real-world Scenarios

Now that you understand the basics of Axios interceptors, let’s explore some real-world scenarios where they can be incredibly useful.

Authentication Handling

Interceptors are often used for handling authentication. You can add an authentication token to every request or refresh tokens when they expire. Here’s an example of how you can use an interceptor for token refreshing:

axios.interceptors.response.use(response => {
  // Check if the response indicates an expired token
  if (response.status === 401) {
    // Perform token refresh and retry the original request
    return refreshToken().then(() => {
      return axios(response.config);
    });
  }
  return response;
}, error => {
  return Promise.reject(error);
});

In this code, we intercept responses with a status code of 401 (Unauthorized) and trigger a token refresh. Once the token is refreshed, we retry the original request.

Authentication handling with interceptors makes it easy to ensure that your API requests are always accompanied by valid authentication tokens.

Global Error Handling

You can use response interceptors to handle errors globally. For instance, you might want to log all errors or show a notification to the user for specific error types:

axios.interceptors.response.use(response => {
  return response;
}, error => {
  // Log the error or display a notification
  console.error('Request failed:', error);
  return Promise.reject(error);
});

This interceptor will catch any errors that occur during HTTP requests and log them to the console.

Global error handling with interceptors ensures that you have a consistent approach to error reporting and handling throughout your application.

Request Loading Indicators:

You can use request interceptors to show loading indicators while requests are in progress and hide them when requests are completed. This provides a better user experience by indicating ongoing network activity.

const loadingIndicatorStart = axios.interceptors.request.use(config => {
  // Show loading indicator
  showLoadingIndicator();
  return config;
});

const loadingIndicatorEnd = axios.interceptors.response.use(response => {
  // Hide loading indicator
  hideLoadingIndicator();
  return response;
}, error => {
  // Hide loading indicator on error
  hideLoadingIndicator();
  return Promise.reject(error);
});

Response Data Transformation

You can use response interceptors to transform data before it reaches your application. For example, you may want to convert all text to uppercase:

axios.interceptors.response.use(response => {
  // Modify the response data
  response.data = response.data.toUpperCase();
  return response;
});

This can be helpful when you want to enforce a specific data format throughout your application.

Caching

You can implement a caching mechanism using interceptors. Intercept requests, check if the data is available in the cache, and return it if it is. If not, proceed with the network request and store the response in the cache for future use.

These are just a few examples of how interceptors can be used in real-world scenarios. Simply put, they provide a powerful way to centralize and manage common tasks across your application.

Removing Interceptors

Axios also allows you to remove interceptors when they are no longer needed. To remove an interceptor, you need to keep a reference to it when you create it and then call eject on the reference.

For example:

const myInterceptor = axios.interceptors.request.use(/* your interceptor function */);

// Later, when you want to remove it
axios.interceptors.request.eject(myInterceptor);

Removing interceptors is useful when you want to change their behavior dynamically or prevent memory leaks.

Conclusion

Axios interceptors are a powerful tool for managing HTTP requests and responses in your web applications. They allow you to handle authentication, error handling, and other global concerns easily. By understanding and effectively using interceptors, you can make your network requests more powerful.

In this article, we’ve covered the basics of request and response interceptors and how they can be applied in real-world scenarios. You can experiment with Axios interceptors in your projects to discover the full range of possibilities they offer for improving your API communication.

Learn more about axios? Then, check the following articles:

Thank you for reading.

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top