In React and Next.js constructor, I am getting “Reference Error: localstorage is not defined”

As everyone already mentioned, Next.js runs both on the client and server. On the server, there isn’t any localStorage, hence the undefined error.

However, an alternative solution is to check if Next.js is running on the server before accessing the localStorage. I.e.,

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

if(!ISSERVER) {
    // Access localStorage
    ...localStorage.get...
}

Leave a Comment