Accessing LocalStorage in NextJS
Ibrahim Adeniyi
Posted on October 5, 2020
I recently migrated a Content Management System from Create React App to NextJS in order to score some SEO points.
One of the challenges I faced was seeing these errors at compile time.
window is undefined
or document is undefined
Window
, and document
are not available on the server. This is why you'll run into these types of errors if you are trying to access window
properties or document
.
In my case, I was persisting my authentication token to localStorage on the previous application.
To avoid running into these undefined errors at compile and build time, you can run a simple check.
if (typeof window !== "undefined") {
localStorage.setItem(key, value)
}
This basically tells your piece of code only to run when it's in the client environment where it can access window
.
Keep hacking.
Posted on October 5, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 10, 2024