Nuxt: window is not defined
How to Resolve Nuxt Error: Window is Not Defined
I’m still enjoying using Nuxt – it has been a great framework organizing Vue.js apps.
I came across an issue today when I was trying to use a 3rd party plugin vue2-scrollspy; I was continually getting “window is not defined”.
After executing the package installation command:
npm install vue2-scrollspy –save
I referenced the component in my code:
import Scrollspy from 'vue2-scrollspy';
export default {
components: {
ScrollSpy
}
}
The error only occurred when I was in 'universal' mode (specified in the nuxt.config.js file); in 'spa' mode, no issue. This tipped me off to realize it probably had something to do with Nuxt server-side rendering; it appeared to be trying to reference the 'window' which wouldn’t exist on the server.
I registered the plugin in the plugins folder as follows:
plugins: [
{ src: '~/plugins/vue2-scrollspy', ssr: false }
],
After restarting the development server I was able to use the plugin with no issues.