DEV Community

Cover image for Using Axios Interceptors In Javascript and Typescript
Mike From CodeSpectre
Mike From CodeSpectre

Posted on

11 3

Using Axios Interceptors In Javascript and Typescript

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);
}
Enter fullscreen mode Exit fullscreen mode

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);
  });
Enter fullscreen mode Exit fullscreen mode

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'}
});
Enter fullscreen mode Exit fullscreen mode

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 */});  
Enter fullscreen mode Exit fullscreen mode

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.

https://twitter.com/codespectreMike

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay