DEV Community

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

Posted on

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.

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.