How to Use Axios Interceptors

fighter-jet

What are Axios Interceptors?

Axios interceptors are built-in functions in Axios that calls for every request or response. Axios interceptors can be used in every request before it is sent or to transform the response before being returned to Axios. In simplest words, you can think of interceptors in Axios as middleware in Express. There are two types of Axios interceptors, request interceptors and response interceptors. Let's dive deeper in both types and see how they work and when should you use them.

If you want to learn more about Axios you can check the Axios Http Client or Axios Github Page

Request Interceptor

The best way to get started with Axios interceptors is to use console.log() in every HTTP request.

const axios = require('axios');

axios.interceptors.request.use(req => {
  console.log(`${req.method} ${req.url}`);
  // You must return the request at the end
  return req;
});

// Result: "get https://codespot.org/get"
await axios.get('https://codespot.org/get');

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

Response Interceptor

As with HTTP requests, we can also use Axios interceptors in every response we get from the server.

const axios = require('axios');

axios.interceptors.response.use(res => {
  console.log(res.data.json);
  // You must return the response at the end
  return res;
});

// Result "post https://codespot.org/post" followed by "{ code: 200 }"
await axios.post('https://httpbin.org/post', { code: 200 });

Authorization Header

The most common case to use Axios interceptors is to set the authorization header. Most of the times the client needs to send a secret token to the server to authorize the user. With interceptors, you can set the authorization header automatically on every request.

axios.interceptors.request.use(req => {
  req.headers.authorization = 'secret token';
  return req;
});

const res = await axios.get('https://codespot.org/get');

Error Handling

With the response interceptors, you can also elegantly handle errors. This is important for Axios because you will get the generic error message "Request failed with status code 404", which usually you won't show to the user.

To handle errors in Axios you should use axios.interceptors.response.use() function which takes two argumentssuccessHandler and errorHandler, The first one successHandler is called if the request is successful and the errorHandler is called if the request failed.

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://codespot.org/status/404').
  then(() => null, err => err);

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

Setting Default Global Configuration

Sometimes you don't want to intercept the request but you want to set up a global configuration. For example, the domain in the URL address you are sending from your application is always the same. You can set up the base URL in someplace where will be run first (for example in React, index.js is a good place). Also you can set authentication token and much more.

//Base URL for every request
axios.defaults.baseURL = "https://codespot.org";
//Base authentication token
axios.defaults.headers.common['Authorization'] = "Token";

index.js

const axios = require('axios');

axios.interceptors.request.use(req => {
  console.log(`${req.method} ${req.url}`);
  return req;
});

//With the base URL set up now, you don't need to put it in the request path
await axios.get('/get');

your-request.js



Top Rated Tutorials:

#js #javascript #axios #http #request

Author: Aleksandar Vasilevski |

Loading...