To fix the reference error: document is not defined in JavaScript, try to shift your script tag at the last of 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:
- Using “document” while using Node.js.
- Using “document” on the server (SSR on NextJS)
- 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.js, ensure 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 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>
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, we are running JavaScript in Node.js; 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 solve reference error: window is not defined

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.