0

What am I doing wrong when injecting a logger to the Nuxt instance?

loglevel.client.js

import log from 'loglevel';

log.setLevel(process.env.LOG_LEVEL || 'debug');

export default ({ app }, inject) => {
  inject('log', log);
  log.debug('logger set up')
}

nuxt.config.js

  plugins: [
    '~/plugins/loglevel.client.js',
    '~/plugins/api.js',
  ],

plugins\api.js

if (process.client) {
  console.log('on client console')
  this.$log.error('on client $log')
}

browser:

api.js?e568:4 on client console
08:22:26.456 api.js?e568:5 Uncaught TypeError: Cannot read properties of undefined (reading '$log')
    at eval (api.js?e568:5:1)
    at Module../plugins/api.js (app.js:1033:1)

1 Answer 1

1

inject makes $log available elsewhere by attaching it as a property to both the root Vue app and to the Nuxt context.

Plugins are ran before the root Vue app is instantiated— you can't access $log via this.$log, unless this refers to the root Vue app instance (like it does in components).

Instead you'll have to access $log via the Nuxt context, which is conveniently available as the first argument to your api.js plugin.

export default ({ $log }) => {
  if (process.client) {
    console.log('on client console')
    $log.error('on client $log')
  }
}

From the docs:

The (Nuxt) context provides additional objects/params from Nuxt to Vue components and is available in special nuxt lifecycle areas like asyncData , fetch , plugins , middleware and nuxtServerInit.

Also, it looks like loglevel is registered as a client-side plugin (loglevel.client.js). That code will not run server side— so you don't have to wrap anything within process.client.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, this seems to work.
I wrapped it with process.client to test this condition. But it fails with "api.js?e568:3 Uncaught ReferenceError: process is not defined".
"process" is a node (ie. server-side) global, not a browser global. There's no such thing as "process.client" on the client side, so you will indeed see this error. Just remove it, you don't need to check you're on the client because you specified api is a client-side only plugin by adding ".client.js" to the filename.
Well, process.client comes from an official Nuxt documentation: axios.nuxtjs.org/helpers
Yup, which is documentation for a universal plugin, not a client-side plugin. Universal plugins run on the server (node), so process.client is recognised by node.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.