Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Localstorage not defined

i am using Nuxt.js for SSR. I have a login system whenever i Log in my App, i get an JSON web token (JWT) and store it in my Localstorage.

The problem is now the SSR. Whenever i try to access the Localstorage it says its not defined. I found an Stackoverflow article about this problem, its because the Code is server side rendered so it has no access to the Localstorage.

I tried the created() lifecycle hook to check if token exist in localstorage, no success. I also tried with nuxtServerInit also no success.

How can i check if token exist in localstorage on the client side or is there any better idea?

like image 979
ilijanovic Avatar asked Oct 21 '25 04:10

ilijanovic


1 Answers

You may call a function on mounted

export default {
  mounted() {
    this.storage();
  },
  methods:{
    storage(){
       localStorage.getItem("authToken");
    }
  }
}

OR use created alongwith process.browser check

export default {
  created() {
    this.storage();
  },
  methods:{
    storage(){
      if (process.browser){
          localStorage.getItem("authToken");
      }
    }
  }
}
like image 144
Bilal Siddiqui Avatar answered Oct 23 '25 20:10

Bilal Siddiqui



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!