Search code examples
javascriptvue.jsvuexnuxt.js

How do I access localStorage in store of NuxtJs?


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.


Solution

  • 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/