Solve - localStorage is not defined Error in JavaScript


Borislav Hadzhiev

Tue Oct 19 20211 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.

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:

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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee