How to solve reference error: document is not defined in JavaScript

To solve reference error: document is not defined in JavaScript, try to shift your script tag at the very last on your body tag or make sure you use the global document variable in the browser. It is the most common error when running an HTML file in the browser.

<!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>

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.

How to solve ReferenceError: document not defined in Node.js

To solve the“ReferenceError: document is not defined” error in Node.jsmake sure you don’t use the document global variable. The variable relates to the Document Object Model, which represents a web page loaded in the browser and can’t be used on the 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>

Now, 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, then it means we are running JavaScript in Node.js, and if it does not, then it means we are in the browser and applying the browser solution in your project.

That’s it for this tutorial.

See also

How to Use a Debugger in JavaScript

How to solve reference error: window is not defined

Leave a Comment