Sometimes, we want to fix ReferenceError: document is not defined with Next.js and JavaScript.
In this article, we’ll look at how to fix ReferenceError: document is not defined with Next.js and JavaScript.
How to fix ReferenceError: document is not defined with Next.js and JavaScript?
To fix ReferenceError: document is not defined with Next.js and JavaScript, we check if document
is defined.
For instance, we write
if (typeof document === "undefined") {
// ...
} else {
// ...
}
in our component to check if document
is undefined with typeof document === "undefined"
.
If it’s not defined, then we render items on server side.
Otherwise, we render client side components.
One reply on “How to fix ReferenceError: document is not defined with Next.js and JavaScript?”
Awesome, thanks for the clear and straightforward solution!