Passing default params in axios using NuxtJS (Interceptors)

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

Image for post
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;
})
;
}
Image for post

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store