NuxtJS pass context, store, inject and axios to plugin

871 Views Asked by At

As my question suggests, I want pass the $axios, context, store and inject functionality to a plugin I writing that integrates with axios and auth0.

I am getting this error...

Cannot read property 'authUrl' of undefined

with this code...

export default ({ $axios }, context, store, inject) => {
const auth = $axios.create({
  baseURL: context.env.authUrl,
  headers: {
    Accept: store.$auth.$storage._state[`_token.auth0`],
    Authorization: `application/vnd.api+json`,
  }
});
}

I imagine it is the way the parameters are being passed to the function? Any help would be much appreciated, thanks!

1

There are 1 best solutions below

0
On

Usually, when you create a plugin, you write it in the form

export default ({ store, $axios }, inject) => {
  // access store or $axios directly
})

or

export default (context, inject) => {
  // here you have context.store or context.$axios
})

See here for reference https://nuxtjs.org/docs/2.x/directory-structure/plugins

Please be aware that the order in which you set your plugins in nuxt.config.js could affect the availability of injected plugins inside the context: if axios plugin is inserted after your custom plugin, you could not be able to use axios itself in it.

However, the Axios module for nuxt has some interesting helpers that could be useful (see https://axios.nuxtjs.org/helpers)