Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

localStorage is not defined NextJS [duplicate]

I was using localStorage in my webApp to store data on client side. But when I've tried to make the app isomorphic, this causes an issue. Due to node is not browser environment, it can't define such objects as 'window', 'localStorage' etc. How do I solve this issue?

like image 394
stkvtflw Avatar asked Nov 16 '22 21:11

stkvtflw


1 Answers

You could use a check whether the code is being executed on the server or on the client side by checking whether module is not 'undefined':

var isNode = typeof module !== 'undefined'

You can then proceed to only executed this code on the client side:

if(!isNode){
   //use the local storage
   var myItem = localStorage.getItem(itemTitle)
}

However, you should already always check whether Storage is defined before using since not all browsers support it:

if(typeof(Storage) !== "undefined"){
   //use the local storage
}
like image 72
TmKVU Avatar answered Mar 05 '23 09:03

TmKVU