How to get access localStorage inside asyncData in Nuxt js

I tried accessing localStorage inside asyncData but the result is "localStorage is not defined"

asyncData(){
     if(localStorage.getItem("myCat")){
        alert(localStorage.getItem("myCat"));
        return;
      }
     
   }

In addition to Jakub Záruba's answer, if you need to access localStorage in asyncData nonetheless, you can modify your if-statement like this:

if (process.client && localStorage.getItem("myCat")) {
  alert(localStorage.getItem("myCat"))
  
  return
}

so you will run this piece of code only on the client-side.


localStorage is not defined because asyncData() is resolved on server while SSR. Variable localStorage can be accessed only if client browser.

See documentation: https://nuxtjs.org/docs/features/data-fetching/. You can use localStorage in hooks mounted(), created(), etc...