I tried accessing localStorage inside asyncData but the result is "localStorage is not defined"
asyncData(){
if(localStorage.getItem("myCat")){
alert(localStorage.getItem("myCat"));
return;
}
}
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.
localStorage in created() hook yetIn 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.
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:
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);
}
}