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
.