28

How do I send custom parameters to the axios interceptor? I am using an interceptor like this:

window.axios.interceptors.request.use(function (config) {
    if (PASSED_PARAM == true) {
        doSomethingAwesome();
    }

    return config;
}, function (error) {    
    return Promise.reject(error);
});

I also have a response interceptor that needs to receive the same parameter.

Fredrik
  • 3,027
  • 8
  • 33
  • 66

9 Answers9

28

Merge params

axios.interceptors.request.use((config) => {
  config.params = {...config.params, my_variable: 'value'}
  return config
})
Piotr Labunski
  • 1,638
  • 4
  • 19
  • 26
Serg
  • 391
  • 3
  • 2
20

The method suggested by @Laurent will cause axios to wipe out all your other parameters and replace it with my_variable, which is may not exactly what you want.

The proper way of adding default parameters instead of replacing it is like this:

axios.defaults.params = {};
axios.interceptors.request.use(function (config) {
    config.params['blah-defaut-param'] = 'blah-blah-default-value';
    return config;
}, function (error) {
    return Promise.reject(error);
});

This works with axios 0.18.1. It does not work with axios 0.19 due to a regression bug..., I believe it will be fixed soon.

Rosdi Kasim
  • 24,267
  • 23
  • 130
  • 154
  • 19
    I feel like all the suggested solutions don't solve the actual question. I think the question is not about adding params inside the interceptor, but adding options/arguments when calling e.g. `axios.get()` which are available inside the interceptor (but ideally not send to the server). So the interceptor can distinguish between requests and adjust it's behavior accordingly. – John Jul 03 '20 at 12:32
  • @John, were you able to figure this out ? – Sathish Sep 29 '21 at 20:14
  • 1
    @Sathish this answer by Tomek C suggests a quite simple solution - although I haven't tried it myself: https://stackoverflow.com/a/67823650/5025424 – John Oct 25 '21 at 13:48
  • This doesn't answer the OPs question, I found it looking to solve the same. Ended up digging through axios source and came up with what I believe is the actual answer: https://stackoverflow.com/a/70647045/822223 – DiamondDrake Jan 10 '22 at 02:00
15

The accepted answer, and the answers on this page seem to have missed what the question is asking.

This question is asking something like "When I call axios can I pass data to the interceptor but not to the server" and the answer is yes. Though it is undocumented and when using typescript you'll have to add a //@ts-ignore.

When you call axios you can pass a config object, (either after the url, or if you're not using a shortcut method like .get/.post the axios function just takes a config object. The good news is that config object is always passed along with the response so you can get to it in the interceptor and in the promise handers.

its available on the response objects as response.config and on the error as error.response.config

//@ts-ignore -- typescript will complain that your param isn't expected on the config object.
axios({
    method: "get",
    url: '/myapi/gocrazy',
    // just piggyback any data you want to the end of config, just don't
    // use any key's that axios is already expecting
    PASSED_PARAM: true
}

//in the interceptor, config is attached to the object, and it keeps any extra keys you tacked on the end.

window.axios.interceptors.request.use(function (config) {
   if (config.PASSED_PARAM == true) {
    doSomethingAwesome();
   }

   return config;
   }, function (error) {
   
   return Promise.reject(error);
});

window.axios.interceptors.response.use(function (response) {
   if (response.config.PASSED_PARAM == true) {
    doSomethingAwesome();
   }

   return response;
   }, function (error) {
   
   if (error.response.config.PASSED_PARAM == true) {
    doSomethingElseAwesome();
   }

   return Promise.reject(error);
});
DiamondDrake
  • 974
  • 8
  • 24
9

Working solution

It's actually fairly simple to add parameters to the query with Axios interceptors when you send data.

axios.interceptors.request.use((config) => {
  config.params = {my_variable: 'value'}
  return config
})
Laurent
  • 2,284
  • 2
  • 21
  • 41
9

axios allows to pass some additional request parameters:

axios.post('/api', `some body`,
    {headers: {'Content-Type': ' text/html;charset=UTF-8'},
    param: true});

and interceptor:

 this.axios.interceptors.request.use(req => {   
    console.log(`${req.method}: ${req.param}`); //output: `/api: true`
    return req;
    });

I have tested it on version: 0.21.1

Tomek C.
  • 584
  • 9
  • 12
1

I ended up using the headers object. Not sure if that is recommended, or if it's anti-pattern. But anyhow it works. I am not entirely sure about how many bytes the header adds to the server request head, but I think it's neglectable.

Fredrik
  • 3,027
  • 8
  • 33
  • 66
  • I was also wondering how to pass parameters and don't want to end up with headers ... If you have alternative solution ? – Laurent Jan 15 '18 at 11:37
  • 1
    Can you please submit a code example. i am having the exact same problem and not sure where and how to insert this param via header – Imnotapotato Jan 09 '21 at 22:08
  • how did you do it? I tried to set a header on the request interceptor and retrieve it on the response interceptor but it doesn't work; axios complains about header cannot be set after sending to client – dragonfly02 Aug 17 '22 at 05:55
  • You should use the solution @Laurent supplied: https://stackoverflow.com/a/48262327/5191800 – Fredrik Aug 17 '22 at 07:31
1

In addition to the answer from DiamondDrake, the global typings can be overridden to not have to 'ts-ignore' the usage:

declare module 'axios' {
    interface AxiosRequestConfig extends OriginalAxiosRequestConfig {
        PASSED_PARAM: boolean;
    }
}
Zack
  • 36
  • 3
0

You cannot pass param but you can update the passed param config. request interceptor logic runs before executing requests. It is kinda middlewares So maybe you need to access to tokens and update the request headers

axios.interceptors.request.use(
  (config) => {
    // or maybe you need to read the stored cookies
    const user = localStorage.getItem("user");   
    if (user) {
      // If user exists get the token
      const token = JSON.parse(user).token;
      // and then update the headers
      config.headers.Authorization = `Bearer ${token}`;
    }   
    // maybe u need to refresh the access tokens, you do it in interceptor
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
0

The answer of https://stackoverflow.com/users/12706095/zack is kinda correct.

You should create an axios.d.ts file including the following lines, the rest is done by TypeScript.

import "axios";

declare module "axios" {
    export interface AxiosRequestConfig {
        /** A custom axios request config param that can be used anywhere now. */
        myParam?: boolean;
     }
 }

Now TypeScript won't bother you anymore when you want to use this custom property anywhere when accessing the AxioRequestConfig, e.g. your interceptor.

See Axios typescript customize AxiosRequestConfig for more info.

Walnussbär
  • 567
  • 5
  • 19