4 Ways To Use Axios Interceptors

Rg45 Wires - Credit Elasticcomputefarm

What is Axios?

Axios is a promise-based HTTP client for the browser and node.js. It comes with many useful defaults like automatically detecting JSON responses and returning an object instead of plain text, throwing an error if the response status code is greater than 400.

What is an axios interceptor?

An Axios interceptor is a function that the library calls every time it sends or receives the request. You can intercept requests or responses before they are handled by “then” or “catch”.

Example:


axios.interceptors.request.use(function (config) {
    
    return config;
  }, function (error) {
    
    return Promise.reject(error);
  });


axios.interceptors.response.use(function (response) {
    
    
    return response;
  }, function (error) {
    
    
    return Promise.reject(error);
  });

You can also remove the interceptor from Axios.

const myInterceptor = axios.interceptors.request.use(function ({});
axios.interceptors.request.eject(myInterceptor);

There is a big chance when building an app that you will use an API that requires some credentials like api_token or a user Auth token. Usually, you will have to append the required headers with every HTTP request you make. Using Axios interceptors, you can set this up once, and anywhere you call your Axios instance, you are sure that the token is there.

axios.interceptors.request.use(req => {
  
  
  req.headers.authorization = ‘Bearer mytoken’;
  return req;
});



const res = await axios.get(‘https://api.example.com’);

Log every request and response using interceptors.

Logging requests can be beneficial, especially when you have a large app and you don’t know where all your requests are triggered. Using an Axios interceptor, you can log every request and response quickly.

const axios = require(‘axios’);

axios.interceptors.request.use(req => {
  console.log(`${JSON.stringify(req, null, 2)}`);
  
  return req;
});

axios.interceptors.response.use(res => {
  console.log(res.data.json);
  
  return res;
});

await axios.post(‘https://example.com/);

Error handling using Axios interceptors

You can use An Axios interceptor to capture all errors and enhance them before reaching your end user. If you use multiple APIs with different error object shapes, you can use an interceptor to transform them into a standard structure.

const axios = require(‘axios’);
axios.interceptors.response.use(
  res => res,
  err => {
    throw new Error(err.response.data.message);
  }
)
const err = await axios.get(‘http://example.com/notfound’).
  catch(err => err);

err.message;

Add rate limiting to requests using interceptors.

Backend resources are limited and can cost a lot of money. As a client, you help reduce the load on your server by rate-limiting your HTTP calls.
Here’s how you can do it using an Axios interceptor.

const axios = require(‘axios’);
const debounce = require('lodash.debounce');
axios.interceptors.request.use(
  res => {
return new Promise((resolve) => {

       debounce(
          () => resolve(config),2000);
       });
    });
  }
)
Load More Related Articles
Load More By john
Load More In Javascript

Leave a Reply

Your email address will not be published. Required fields are marked *