0

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

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

3 Answers 3

2

localStorage is not defined because asyncData() is resolved on the server during SSR. The localStorage variable is only accessible in the client browser.

See documentation: https://nuxtjs.org/docs/features/data-fetching/. You can use localStorage in the mounted() hook.

Sign up to request clarification or add additional context in comments.

1 Comment

You can't use localStorage in created() hook yet
2

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.

Comments

0

In the Options API, use the asyncData method to fetch data before the component is created. It runs on the server during SSR and on the client during navigation.

If you're using the Composition API, use useAsyncData. It runs once:

  1. On server-side during initial load (without re-fetching on client).
  2. On client-side when navigating between pages.

Since localStorage is only available on the client, check import.meta.client or process.client before accessing it.

You can disable SSR like this:

useAsyncData('some-key', () => {
  if (import.meta.client) {
    // # your code
    const val = localStorage.getItem("myKey");
    if (val) alert(val);

  }
}, { server: false }); // disabled SSR 

In the Options API, you cannot use localStorage inside asyncData because it runs on the server. Instead, use the mounted() hook to access client-only features like localStorage:

export default {
  mounted() {
    // # your code
    const val = localStorage.getItem("myKey");
    if (val) alert(val);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.