How to Fix ReferenceError: document is not defined in JavaScript

There are specific reasons for the ReferenceError: document is not defined error, such as:

  1. Using document while using Node.js.
  2. Using document on the server (SSR on NextJS)
  3. Misspelled the global variables; global variables should be in lower cases.
<!DOCTYPE html>
<html lang="en">
 <head>
   <meta charset="UTF-8" />
 </head>

 <body>
   <!-- Your HTML Code here -->

   <!-- JavaScript at bottom of body -->
  <script type="module" src="app.js"></script>
 </body>
</html>

How to fix it?

To fix the reference error: document is not definedtry to shift your script tag at the last of your body tag or make sure you use the global document variable in the browser.

The variable relates to the Document Object Model, which represents a web page loaded in the browser and can’t be used on a server-side platform like Node.js.

Write the below code in the index.html file.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <script src=”app.js”></script>
  <title>ReferenceError: Document is not defined</title>
</head>

<body>
  <h1>Body of the HTML Doc</h1>
  <div id=”msg”>
  <p>This is a message.</p>
  </div>
</body>

</html>

Write the below code inside the app.js.

console.log("This is a ReferenceError: document is not defined");
var x = document.getElementById("msg");
console.log(x);

If you run the file, it will give the following error.

ReferenceError: document is not defined

You cannot use the document object on the server-side platform like Node.js because Node.js does not have a global “window” object. However, if the “window” global is defined, we are on the browser and can use the “document” variable.

Refer to the below fix code.

console.log("Fixing Document is not defined in NodeJS");

if (typeof window !== "undefined") {
  console.log("In Browser");
  var x = document.getElementById("msg");
  console.log(x);
}
else {
  console.log("In nodeJS");
}

If the window object is undefined, we are running JavaScript in Node.js; if it is not, then it means we are in the browser and applying the browser solution in your project.

See also

How to solve reference error: window is not defined