Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 967
Rogelio Avatar asked Jan 29 '26 10:01

Rogelio


2 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)
}
}
like image 120
Raffobaffo Avatar answered Feb 01 '26 02:02

Raffobaffo


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/

like image 30
Ifaruki Avatar answered Feb 01 '26 02:02

Ifaruki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!