React – “localStorage is not defined” error showing

When you’re rendering on the server, you do not have a browser and thus you do not have access to all the APIs that the browser provides, including localStorage.

In JavaScript code that is running both on the server and on the client (browser), it is common practice to guard against with an if clause that checks if window is defined. “Window” is the root object provided by the browser for all the APIs that are provided by the browser.

Example:

if (typeof window !== 'undefined') {
    console.log('we are running on the client')
} else {
    console.log('we are running on the server');
}

In your case, you want to put your call to localStorage in such an if clause, for example:

if (typeof window !== 'undefined') {
    localStorage.setItem('myCat', 'Tom');
}

Leave a Comment