Passing default params in axios using NuxtJS (Interceptors)

Bikram KC
Nov 18, 2020

Sometimes you might need to add default params to axios request. I have also faced a similar situation. I thought it might help you too.
I was working on a multilingual app and need to pass the request with the selected language.

I have added @nuxtjs/axios as module. If you haven’t then add @nuxtjs/axios module.

You will need to extend the axios to customize the default behaviour. Then you need to create a file named axios.js inside plugins directory.
Now add your file like the following to your nuxt.config.js

export default function ({ ctx, $axios, redirect, $auth }) {
$axios.onRequest(config => {
config.params = config.params || {};
//add your params here
config.params['lang'] = window.$nuxt.$i18n.locale;
return config;
})
;
}

In every axios request, your extra params will be added automatically.

You can also add other interceptors like the following if needed:

onRequest(config)
onResponse(response)
onError(err)
onRequestError(err)
onResponseError(err)

Follow official @nuxt/axios document: https://axios.nuxtjs.org/helpers

--

--