How to avoid the "localStorage not defined" error on the server in an isomorphic ReactJS application?

I used localStorage in my webApp to store client-side data. But when I tried to make the application isomorphic, this causes a problem. Because node is not a browser environment, it cannot define objects such as "window", "localStorage", etc. How to solve this problem?

+11
reactjs isomorphic-javascript
source share
2 answers

You can check if the code is running on the server or on the client side by checking if the module is not 'undefined' :

 var isNode = typeof module !== 'undefined' 

Then you can only proceed to the execution of this code on the client side:

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

However, you should always check if Storage defined before use, as not all browsers support it:

 if(typeof(Storage) !== "undefined"){ //use the local storage } 
+10
source share

The standard has specific support for such problems.

All you have to do is add a comment informing the standard that there is a variable provided by the global scope.

 // MyStuff.js /* global localStorage */ // Use localStorage below with no linter errors 
+1
source share

All Articles