Skip to content

How to solve the document is not defined error

New Course Coming Soon:

Get Really Good at Git

Here’s how to fix the “referenceerror: document is not defined” error that you might have in Node.js or with a tool like Next.js.

document is an object that’s made available by the browser, and it’s not available in a server-side JavaScript environment.

I describe the document object is details in my extensive DOM Document Object Model guide.

With Node.js in particular there’s no way to workaround the problem - you must find the particular place where document is used, and revisit the code to figure out why you are accessing the document object.

You are running frontend code in a backend environment.

In Next.js you can fix this problem by wrapping the code you run in a conditional.

The code might be running in both situations - frontend, when you navigate to a page using a link, and server-side if you require server-side into your page, for example by running getServerSideProps().

In this case, you can limit the reference to document into a conditional that checks if the window object is available, like this:

if (typeof window !== 'undefined') {
  //here `window` is available, so `window.document` (or simply `document`) is available too
}

And this will fix your problem, since you only run anything inside the conditional in a browser environment.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: