Axios config default GET param

Here it is:

axios.defaults.params = {}
axios.defaults.params['api-key'] = secret

If you need to call a function before each axios request, you should use an interceptor.


I struggled to get this to work with axios instances using the two most commonly suggested methods:

// method 1: setting axios.defaults.params at the class level
axios.defaults.params = {}
axios.defaults.params['api-key'] = secret

and

// method 2: setting the `params` attribute at an instance level
const axClient = axios.create({
    baseURL: process.env.VUE_APP_BASE_URL,
    params: {
        api-key: process.env.VUE_APP_API_KEY
    }
});

I did however, manage to get it working nicely using interceptors like this:

// create an instance with default properties
const axClient = axios.create({
    baseURL: process.env.VUE_APP_BASE_URL,
});

axClient.interceptors.request.use((config) => {
    // use config.params if it has been set
    config.params = config.params || {};
    // add any client instance specific params to config
    config.params['api-key'] = process.env.VUE_APP_API_KEY;
    return config;
});

The benefit of this approach is that the instance level params can be dynamic/computed per request if needed.

As a (slightly contrived) example, if you needed to add a JWT to each request (including any logic to fetch it from your storage method of choice) and even react to the logic around that. So in this toy example, if the user doesn't have a JWT in storage, redirect them to the login page instead of making the request.

Tags:

Vue.Js

Axios