How to intercept responses with Axios

What is an interceptor?

Upon sending a request, we'll receive either a success response or an error response. In axios, the success response is handled in the then block, and the error is handled inside the catch block.

Using Interceptors, we can intercept the requests or responses before they are handled by the then or catch block.

Intercept responses with axios

We can use the Interceptors to intercept the response before the then block handles the response.

Read this Answer to learn about axios.

Syntax

const interceptor = axios.interceptors.response.use(successFn, errorFn);
Syntax to add interceptor to response

Arguments

When adding an interceptor to the response we need to pass two functions as an argument as follows:

  1. successFunction – This function is triggered if the status code comes under 2xx. We need to return the response object from this function.

  2. errorFunction – This function is triggered if the status code is outside the range of 2xx.

Return value

We will get the interceptor instance as a return value which can be used to remove the interceptors later.

Example

Let's write an example to use the Interceptors. Here we will load the dummy user data from JSONPlaceHolder website. Inside Interceptors we will modify the structure of the received user data.

Console
Adding interceptor for response

Explanation

Let's discuss the code above:

  • Line 6: Include the axios library.

  • Lines 10–19: Create a function cleanData that will take the user's data as an argument and return an array of user data. The returned user object will only contain the name and email.

  • Lines 23–30: Add the interceptors for the response. Inside the success callback function, invoke the cleanData function with response data as an argument. The data returned from the cleanData function is set as the data of the response object.

  • Lines 32–35: Make a GET request to get the user's data. Once the server returns the response the interceptors will intercept the response after that the then block will be executed.

Free Resources

Attributions:
  1. undefined by undefined
Copyright ©2025 Educative, Inc. All rights reserved