Categories
React Answers

How to fix ‘Reference Error: localstorage is not defined’ with React and Next.js?

Spread the love

To fix ‘Reference Error: localstorage is not defined’ with React and Next.js, we should check if window is defined before trying to use local storage.

For instance, we write

const ISSERVER = typeof window === "undefined";

if (!ISSERVER) {
  localStorage.get("...");
}

to check if window is 'undefined' with typeof.

If it’s defined, then the app isn’t server-side rendered and we can use browser APIs like localStorage.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *