Categories
React Answers

How to fix ReferenceError: document is not defined with Next.js and JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to fix ReferenceError: document is not defined with Next.js and JavaScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *