ReferenceError: localStorage is not defined

localStorage is a Web API provided by the browser. When we are on the server then we do not have access to all the browser-provided Web APIs.

When we are writing code using JavaScript especially in React we have options to render both on server and client (browser) end. As localStorage is a Web API for the browser, we can make sure that we call it from the client end by using a check.

It is common practice to check with an if condition 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.

Check for borwser or server

if (typeof window !== 'undefined') {
    console.log('Rendering on browser or client')
} else {
    console.log('Rendering on server');
}

If we want to use localStorage we can add the following condition to define localStorage.

if (typeof window !== 'undefined') {
    localStorage.setItem('username', 'Joe Smith');
}