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
You don’t have localStorage because there is no such thing in Node.js environment. You also don’t have
window
anddocument
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.
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: