Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Axios Interceptors Sample Code
    Axios interceptors request interceptor response interceptor Axios setup custom headers error handling request duration JavaScript


Axios Interceptors Sample Code


Here is a concise and accurate response to the query, based on the provided search results:

Axios interceptors are a powerful feature that allow you to intercept and modify requests and responses before they are handled by the application. Here is a sample code for using Axios interceptors:

javascript
// Add a request interceptor
axios.interceptors.request.use(
  (config) => {
    // Do something before request is sent
    config.headers['Authorization'] = 'Bearer <your_access_token>';
    config.params = { ...config.params, version: '1.0.0' };
    config.meta = config.meta || {};
    config.meta.requestStartedAt = new Date().getTime();
    return config;
  },
  (error) => {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
axios.interceptors.response.use(
  (response) => {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    const requestDuration = new Date().getTime() - response.config.meta.requestStartedAt;
    console.log(`Request took ${requestDuration}ms`);
    return response;
  },
  (error) => {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return parseError(error.response?.data?.messages);
  }
);

// Utility function to parse error response
function parseError(messages) {
  if (messages) {
    if (messages instanceof Array) {
      return Promise.reject({ messages: messages });
    } else {
      return Promise.reject({ messages: [messages] });
    }
  } else {
    return Promise.reject({ messages: ['An error occurred'] });
  }
}

This code sets up two interceptors:

1. Request Interceptor: This interceptor adds an `Authorization` header with a bearer token, adds a `version` parameter to the request, and stores the request start time in the `config.meta` object.

2. Response Interceptor: This interceptor calculates the request duration by subtracting the start time from the current time, logs the duration, and then handles any error responses by parsing the error messages.[1][2][3][4][5]

The `parseError` function is a utility function that normalizes the error response data into a consistent format.

This sample code demonstrates how Axios interceptors can be used to add custom logic to the request and response lifecycle, such as adding headers, transforming data, and handling errors.[1][2][3][4][5]

Citations:
[1] https://stackoverflow.com/questions/52737078/how-can-you-use-axios-interceptors
[2] https://axios-http.com/docs/interceptors
[3] https://dev.to/sundarbadagala081/axios-interceptors-34b2
[4] https://geshan.com.np/blog/2022/12/axios-interceptors/
[5] https://gist.github.com/moreta/fb2625c59aa788009b1f7ce8e44ac559