Khaled Garbaya

Engineering Leader, Software Developer & Educator

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:

1// Add a request interceptor 2axios.interceptors.request.use(function (config) { 3 // Do something before request is sent 4 return config; 5 }, function (error) { 6 // Do something with request error 7 return Promise.reject(error); 8 }); 9 10// Add a response interceptor 11axios.interceptors.response.use(function (response) { 12 // Any status code that lie within the range of 2xx cause this function to trigger 13 // Do something with response data 14 return response; 15 }, function (error) { 16 // Any status codes that falls outside the range of 2xx cause this function to trigger 17 // Do something with response error 18 return Promise.reject(error); 19 }); 20

You can also remove the interceptor from Axios.

1const myInterceptor = axios.interceptors.request.use(function ({/*...*/}); 2axios.interceptors.request.eject(myInterceptor); 3

Inject auth token header in every request using interceptors

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.

1axios.interceptors.request.use(req => { 2 // `req` is the Axios request config, so you can modify 3 // the `headers`. 4 req.headers.authorization = ‘Bearer mytoken’; 5 return req; 6}); 7 8// Automatically sets the authorization header because 9// of the request interceptor 10const res = await axios.get(‘https://api.example.com’); 11

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.

1const axios = require(‘axios’); 2 3axios.interceptors.request.use(req => { 4 console.log(`${JSON.stringify(req, null, 2)}`); 5 // you must return the request object after you are done 6 return req; 7}); 8 9axios.interceptors.response.use(res => { 10 console.log(res.data.json); 11 // you must return the response object after you are done 12 return res; 13}); 14 15await axios.post(‘https://example.com/); 16

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.

1const axios = require(‘axios’); 2axios.interceptors.response.use( 3 res => res, 4 err => { 5 throw new Error(err.response.data.message); 6 } 7) 8const err = await axios.get(‘http://example.com/notfound’). 9 catch(err => err); 10// “Could not find page /notfound” 11err.message; 12

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.

1const axios = require(‘axios’); 2const debounce = require('lodash.debounce'); 3axios.interceptors.request.use( 4 res => { 5return new Promise((resolve) => { 6// only fire a request every 2 sec 7 debounce( 8 () => resolve(config),2000); 9 }); 10 }); 11 } 12) 13

Next one in your inbox

no spam only content