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
:
VueSession.install = function(Vue, options) { if (options && 'persist' in options && options.persist) STORAGE = window.localStorage; else STORAGE = window.sessionStorage; Vue.prototype.$session = { flash: { parent: function() { return Vue.prototype.$session; },
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.
To fix the 'document is not defined' error in Nuxt. js, we can wrap our client side code with the client-only component. to wrap the the client side only your-component component with client-only so that it's only rendered in the browser.
Nuxt offers better SEO improvement with its server-side rendering feature, faster development with an auto-generic router, public share features, and management with great configuration options and meta tags methods, automatic code splitting with pre-rendered pages — all of this is impossible or extremely complex to ...
UPDATED AUGUST 2021
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 then add it to your 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' } ]
There is no window object on the server side rendering side. But the quick fix is to check process.browser
.
created(){ if (process.browser){ console.log(window.innerWidth, window.innerHeight); } }
This is a little bit sloppy but it works. Here's a good writeup about how to use plugins to do it better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With