How to attach axios / axios interceptor to Nuxt globally ?

13,673

Solution 1

you can create a plugin called axios (/plugins/axios.js)

import Vue from 'vue';
import axios from 'axios';

axios.interceptors.request.use((config) => {
  // Do something before request is sent
  return config;
}, function (error) {
  // Do something with request error
  return Promise.reject(error);
});

Vue.use(axios);

then define this in nuxt.config.js

module.exports = {
    //....

    plugins: [
      '~/plugins/axios',
    ],

    //....
};

thats all, your interceptor is now working globally

Solution 2

It's hidden in the documentation - https://nuxtjs.org/docs/2.x/directory-structure/plugins

See number 3 of the first photo:

// plugins/axios.js
export default function ({ $axios, redirect }) {
    $axios.onError(error => {
        if (error.response.status == 404) {
            redirect('/sorry')
        }
    })
}

then define this in nuxt.config.js

module.exports = {
    //....

    plugins: [
      '~/plugins/axios',
    ],

    //....
};

Solution 3

Maybe will be helpful for someone. It just sets the lang parameter for every request.

Сreate a plugin called axios (/plugins/axios.js). Put it there:

export default function ({ $axios, app, redirect }) {
  $axios.onRequest(config => {
    config.params = config.params || {}; // get existing parameters
    config.params['lang'] = app.i18n.locale;
  })

  $axios.onError(error => {
    const code = parseInt(error.response && error.response.status)
    if (code === 400) {
      redirect('/400')
    }
  })
}

Add in nuxt.config.js:

module.exports = {
    plugins: [
      '~/plugins/axios'
    ]
};

Solution 4

Create a new module, call it request.js for example.

import axios from 'axios'
const instance = axios.create({
  baseURL: 'http://example.org' // if you have one
})

// Put all interceptors on this instance
instance.interceptors.response.use(r => r)

export default instance

Then simply import that instance whenever you need it and use it like it was a normal axios instance:

import request from './request'

await request.get('/endpoint')
// or use promises
request.get('/endpoint').then(data => data)

If you really need it globally you can use the following code in your entry point of the application:

import request from './request'
global.request = request
// use it:
await request.get('example.org')

Or you can add it to the vue protype

Vue.prototype.$request = request
// in your component:
this.$request.get()

I'd advice against it though.

Share:
13,673
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    how would i go about attaching axios / axios interceptor globally to nuxt (so its available everywhere), same how i18n is attached ?

    The idea is that i would like to have a global axios interceptor that every single request goes through that interceptor.

    Thanks

  • Admin
    Admin almost 6 years
    id still have to import request module in every single component... is there a way to attach that to a global nuxt object ?
  • Philip Feldmann
    Philip Feldmann almost 6 years
    @rvsted yes you can, I've updated my answer accordingly but I don't suggest doing it, as the module import is just cleaner. You can also attach it to the vue instance by adding it to its prototype if you needed to.
  • zerohedge
    zerohedge almost 5 years
    Is there any way to access state from this plugin?
  • manoi
    manoi over 4 years
    yes, you can import the store und use it import store from '@/store/index'; store.getters['user/name']; in store you have to export getters, actions, etc export const getters = { name: (state, getters) => {...} }
  • PirateApp
    PirateApp over 2 years
    why plugin? why not middleware