skip to Main Content

I’m working on a Nuxt JS application which utilises LocalStorage. When compiling in SPA mode it functions correctly, however I need to switch my project to universal mode to get my SEO meta titles and descriptions to work when generating my project, after switching I get an error on a few pages which utilise LocalStorage:

localStorage is not defined

Has anyone got any suggestions to fix this?

2

Answers


  1. You don’t have localStorage because there is no such thing in Node.js environment. You also don’t have window and document objects.

    https://ssr.vuejs.org/guide/universal.html#access-to-platform-specific-apis

    Nuxt.js uses Vue SSR under the hood.

    However, you still have a store (Vuex). And it will be synchronized between node and browser.

    Login or Signup to reply.
  2. I needed data to persist between sessions for GDPR. You can use the mounted life cycle event and wait for window.localStorage to be available. Then assign it to a data property and add a v-if in a wrapper tag so the page doesn’t start rendering before localeStorage is available. I’m doing this with a static nuxt build:

    <div v-if="localStorageReady">
        Awesome stuff here...
    </div>
    
    data() {
      return {
        localStorageReady: false,
      }
    },
    
    mounted() {
      if (window.localStorage) {
        this.localStorageReady = true
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search