Solve - localStorage is not defined Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Solve - localStorage is not defined Error #

The "ReferenceError: localStorage is not defined" error occurs for multiple reasons:

  1. Using localStorage in Node.js.
  2. Using localStorage on the server (e.g. server side rendering in Next.js).
  3. Misspelled the localStorage global variable (should be camelCase).

referenceerror localstorage is not defined

The localStorage property is a property on the window object, therefore it's not available on the server.

index.js
console.log(localStorage === window.localStorage); // 👉️ true localStorage.setItem('name', 'Tom'); console.log(localStorage.getItem('name')); // 👉️ "Tom"
If you're getting the error in the browser, make sure that you have not misspelled the localStorage keyword (should be camelCase).

If you're using React.js or Next.js and you need to check if you're on the browser (can use localStorage) or on the server (can't use localStorage), you can do this in the following way:

index.js
if (typeof window !== 'undefined') { console.log('You are on the browser') // 👉️ can use localStorage here } else { console.log('You are on the server') // 👉️ can't use localStorage }

We check if the global window variable does not have a type of undefined. If the window global is defined, we are on the browser and can use the localStorage object.

To solve the "ReferenceError: localStorage is not defined" error, make sure to only use the localStorage object in the browser. The localStorage property is defined on the window object and is not available on the server - e.g. in Node.js or when using server side rendering with Next.js.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.