“window is not defined” in Nuxt.js

HM.Park picture HM.Park · Mar 4, 2019 · Viewed 24.3k times · Source

I get an error porting from Vue.js to Nuxt.js.

I am trying to use vue-session in node_modules. It compiles successfully, but in the browser I see the error:

ReferenceError window is not defined

node_modules\vue-session\index.js:

so, I followed this documentation:

rewardadd.vue:

import VueSession from 'vue-session';

Vue.use(VueSession);

if (process.client) {
  require('vue-session');
}

nuxt.config.js:

  build: {
    vendor: ['vue-session'],

But I still cannot solve this problem.

Answer

innocentwkc picture innocentwkc · Oct 30, 2019

UPDATED JULY 2020

The Window is not defined error results from nodejs server side scripts not recognising the window object which is native to browsers only.

As of nuxt v2.4 you don't need to add the process.client or process.browser object.

Typically your nuxt plugin directory is structured as below:

~/plugins/myplugin.js

import Vue from 'vue';
// your imported custom plugin or in this scenario the 'vue-session' plugin
import VueSession from 'vue-session';

Vue.use(VueSession);

And then in your nuxt.config.js you can now add plugins to your project using the two methods below:

METHOD 1:

Add the mode property with the value 'client' to your plugin

plugins: [
    { src: '~/plugins/myplugin.js', mode: 'client' }
  ]

METHOD 2: (Simpler in my opinion)

Rename your plugin with the extension .client.js and the add it to you plugins in the nuxt.config.js plugins. Nuxt 2.4.x will recognize the plugin extension as to be rendered on the server side .server.js or the client side .client.js depending on the extension used.

NOTE: Adding the file without either the .client.js or .server.js extensions will render the plugin on both the client side and the server side.Read more here.

plugins: [
    { src: '~/plugins/myplugin.client.js' }
  ]