Axios is a robust, easy to use, promise-based http client for javascript and node.js. Axios provides developers with tools to handle all http-related functions. Axios interceptors are one of the essential tools Axios provides us for dealing with HTTP requests and responses.
Axios is a great way to handle any sort of HTTP requests in javascript or typescript, and I use it in all of my projects that require accessing an API. It provides all the necessary functions for passing data to and from APIs and then accessing it on the frontend.
If you've never used Axios, I suggest checking out the documentation here: https://axios-http.com/docs/intro
Interceptors
Interceptors are exactly what they sound like. They "intercept" requests and responses.
This can be useful if you need to perform some validation on the data before sending a request or when retrieving a response.
Here's an example of intercepting a request:
axios.interceptors.request.use(function (req) {
// if name not in request config then reject
if (!req.name) {
return Promise.reject("Error: Please Include a name");
}
}, function(err) {
return Promise.reject(err);
}
You can also use it on responses like this:
axios.interceptors.response.use(function (res) {
// filter out null or undefined values using filter()
let filtered_names = res?.data?.names.filter((a) => a);
return filtered_names;
}, function (err) {
return Promise.reject(err);
});
In the response example, we're filtering an array of names that was passed back to make sure no null or undefined values are included.
Custom Axios Instances
One of the nicest use cases of Axios interceptors is the ability to add them to a custom axios instance for your project.
If you are unfamiliar with Axios instances, it is a way to add all the data you need to send with each request automatically.
For example: in our project we need to always have an access token header and the base URL of our api. We can create a custom instance like this:
const customInstance = axios.create({
baseURL: 'https://mytestingapi.com/api',
headers: {'access_token': 'custom_token'}
});
Now whenever we need to perform a request with Axios, we can call customInstance instead and all our data will be included automatically.
Adding Interceptors To Custom Instances
Adding interceptors to Axios instances is done in the same way you'd do it normally, except instead of using the axios keyword, we'll use the name of our instance.
customInstance.interceptors.request.use(function(){/* do stuff here */});
Conclusion
I hope you found this simple introduction to interceptors to be useful. It is worth checking out the Axios documentation if you want to learn more.
Also don't forget to follow me on twitter @codespectremike to get notifications for my latest videos and articles.
Top comments (0)