Axios Interceptors

Jun 8, 2020

Axios interceptors are functions that Axios calls for every request. You can use interceptors to transform the request before Axios sends it, or transform the response before Axios returns the response to your code.

You can think of interceptors as Axios' equivalent to middleware in Express or Mongoose.

The easiest way to get started with interceptors is to write one that console.log()'s every HTTP request. Since Axios calls interceptors for you, you only have to write one interceptor instead of calling console.log() every time.

const axios = require('axios');

axios.interceptors.request.use(req => {
  console.log(`${req.method} ${req.url}`);
  // Important: request interceptors **must** return the request.
  return req;
});

// Prints "get https://httpbin.org/get"
await axios.get('https://httpbin.org/get');

// Prints "post https://httpbin.org/post"
await axios.post('https://httpbin.org/post', {});

There are two types of interceptors: request interceptors and response interceptors.

The previous example was a request interceptor. Axios calls request interceptors before sending the request, so you can use request interceptors to modify the request.

Axios calls response interceptors after it sends the request and receives a response. The res parameter to interceptors is the Axios response object, the same object you get when you do await axios.get(). Below is a simple response interceptor that prints the response.

const axios = require('axios');

axios.interceptors.request.use(req => {
  console.log(`${req.method} ${req.url}`);
  // Important: request interceptors **must** return the request.
  return req;
});

axios.interceptors.response.use(res => {
  console.log(res.data.json);
  // Important: response interceptors **must** return the response.
  return res;
});

// Prints "post https://httpbin.org/post" followed by "{ answer: 42 }"
await axios.post('https://httpbin.org/post', { answer: 42 });

Automatically Set the Authorization Header

One of the most common use cases for interceptors is handling authorization. Typically, the way a client app proves to a server that the user is logged in is by sending a secret token in the authorization header. Interceptors let you set the authorization header automatically on all requests as shown below.

axios.interceptors.request.use(req => {
  // `req` is the Axios request config, so you can modify
  // the `headers`.
  req.headers.authorization = 'my secret token';
  return req;
});

// Automatically sets the authorization header because
// of the request interceptor
const res = await axios.get('https://httpbin.org/get');

Error Handling

Response interceptors also let you handle errors. This is important because Axios' default error message is "Request failed with status code 404", which usually isn't what you want to show to your end user.

The axios.interceptors.response.use() function takes 2 function parameters: successHandler and errorHandler. Axios calls successHandler if the request succeeded, or errorHandler if the request failed. You can write your own errorHandler to transform errors as shown below.

Just make sure to rethrow an error in your errorHandler, otherwise Axios will treat it as a successful request!

axios.interceptors.response.use(
  res => res,
  err => {
    if (err.response.status === 404) {
      throw new Error(`${err.config.url} not found`);
    }
    throw err;
  }
);

// Automatically sets the authorization header because
// of the request interceptor
const err = await axios.get('https://httpbin.org/status/404').
  then(() => null, err => err);

err.message; // "https://httpbin.org/status/404 not found"

More Axios Tutorials