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.
Top comments (13)
Nice trick, but I think it would make more sense to use
useEffect
method, did you try it?Because some time we need to copy and paste code, and after code doesn't work after pasting so developers 😯😯😯😯😯.
Your Code have some mistakes check out this 👍
You may find yourself in a situation where you need access to localStorage outside a react component. In that case useEffect cannot help.
window.localStorage (spelling)
Trying to making a reusable function
This function for get data from localstorage
key is required
Set data to localstorage
Any new method to use window in nextjs
That's nice
This leads to a warning of type "Expected server HTML to contain a matching" on Next 10 BTW: stackoverflow.com/questions/464436...
remember, never create a function for window type checking.
it always must be an explicit type checking or it will not work
Right way to do it:
Wrong way:
read more and reason for this problem: Next.js GitHub issues page
what if i want to access local storage inside redux reducer ?
That's nice, but next time add a
js
tag to the code block to make it more readable.Example:
Thank you
Thanks for the great post !!!!!!
Thanks mate!
Works the same with sessionStorage