vue.jsnuxt.jsbugsnag

Understanding context and app methods in NUXT


I am trying to use bugsnagClient and its notify method in plugins/axios.js I have this code in plugins/bugsnag.js

import Vue from "vue"
import bugsnag from "@bugsnag/js"
import bugsnagVue from "@bugsnag/plugin-vue"

// const bugsnagClient = bugsnag(`${process.env.BUGSNAG_API_KEY}`)
var bugsnagClient = bugsnag({
  apiKey: "",
  notifyReleaseStages: ["production"]
})

bugsnagClient.use(bugsnagVue, Vue)

I want to attach a method to app or context as

export default ({ app }, inject) => {
  function bugsnagNotify(error) {
    return bugsnagClient.notify(new Error(error))
  }
  // Set the function directly on the context.app object
  app.bugsnagNotify = bugsnagNotify
}

And I want to use it in plugins/axios.js

export default function({ store, app }) {
  if (store.getters.token) {
    console.log(app.bugsnagNotify("ss"))
    app.$axios.setToken(store.getters.token, "Bearer")
  } else {
    //app.$bugsnag.notify(new Error("Bearer tooken is missing in Axios request."))
  }
}

In this file, when I do console.log for just app

I can see bugsnagNotify: ƒ bugsnagNotify(error)

but when I call app.bugsnagNotify("error") I only get error such as VM73165:37 TypeError: app.bugsnagNotify is not a function

I have also tried this in plugins/bugsnag.js

export default (ctx, inject) => {
  inject('bugsnag', bugsnagClient)
}

I only get an error as

app.$bugsnag.notify(new Error("Bearer tooken is missing in Axios request."))

Solution

  • If you are injecting into context inside one plugin and want to use that function inside another, you need to make sure that the plugin in which you are injecting comes first inside nuxt.config.js

    ...
    plugins: [
      '~/plugins/bugsnag.js',
      '~/plugins/axios.js'
    ],
    ...