Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Armando Castillejos
The "ReferenceError: localStorage is not defined" error occurs for multiple reasons:
localStorage
in Node.js.localStorage
on the server (e.g. server side rendering in Next.js).localStorage
global variable (should be camelCase).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"
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.