How do I access localStorage in store of NuxtJs?

Viewed 7222

I'm trying to get a value from localStorage to determine the value of a variable in store. I remember trying something similar with vuejs about a year ago and it seemed to work. I also have no issues with this on Reactjs. But for some reason i keep getting this error when doing the same in Nuxt

enter image description here

enter image description here

this is my user.js file

export const state = () => ({
  isLoggedIn: !!localStorage.getItem('userDetails')
})

export const mutations = {
  login(state) {
    state.isLoggedIn = true;
  },
  logout(state) {
    window.localStorage.clear()
    state.isLoggedIn = false;
  }
}

am i approaching this problem wrong? or is this not supposed to work? Any help is appreciated.

5 Answers

When you use SSR you don't have access to the browser storage.

To do a workaround, you can dispatch an action on the mounted component hook.

mounted() {

 if(!process.client) return;
 const savedData = localStorage.getItem("userDetails");
 if(savedData){
    this.$store.commit('myMutation',savedData)
}
}

Try it like this:

isLoggedIn: process.server ? '' : !!localStorage.getItem('userDetails')

The problem is that you try to access the localstorage while nuxt is on the server side. you need to check with process.server if you are on the server side or not. It returns either true or false.

I didnt tested it but with this ternary operator it should work.

Here: https://nuxtjs.org/faq/window-document-undefined/

I can see that you have not set any localstorage. Please set localstorage by

localstorage.setItem()

Related