DEV Community

Cover image for How to intercept a request with Axios
Diego Souza
Diego Souza

Posted on

2 1

How to intercept a request with Axios

Maybe, in your application you need to do a request with Axios using a token. But, you don't have a token yet. So, the application makes a request and then return an error with status code 401.

Fortunately, the Axios have a middleware that can help us to intercept the requests. For this, use the interceptors of instance of Axios thas was created.

import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.spotify.com/v1/',
});

api.interceptors.request.use(
  (request) => {
    if (api.defaults.headers.authorization) return request;

    throw new axios.Cancel('Token is not available. Do login, please.');
  },
  (error) => {
    return Promise.reject(error);
  },
);

export default api;
Enter fullscreen mode Exit fullscreen mode

This code will avoid that the application from making the request and showing a error in the browser's console. The code check if exists a token in property Authorization, if a token is not found, the request won't be executed, returning an error from own Axios.

throw new axios.Cancel('Token is not available. Do login, please.');
Enter fullscreen mode Exit fullscreen mode

This function Cancel from Axios is very important.

Do you know any other way to do this? Share with the community.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (2)

Collapse
 
bias profile image
Tobias Nickel

so you intersected and not really canceled. its like an if statement injected o the axios client, to be checked before send. so, something that isn't started can not be canceled.

Still, the use of this intersector is good.

Collapse
 
deesouza profile image
Diego Souza

You have reason. I modified the title of the post. Thanks a lot.

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

View demo

👋 Kindness is contagious

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

Okay