ReferenceError: document is not defined in JavaScript

December 8, 2022

ReferenceError: document is not defined in JavaScript

This guide is part of the “Common JavaScript Errors” series. It’s focused entirely on providing quick and easy solutions for JavaScript-related problems.


The "ReferenceError: document is not defined" error is thrown when the code tries to access the document object, but the object is not defined in the current scope. This error usually occurs when the code is running in a non-browser environment, such as in a Node.js server-side application, and does not have access to the document object that is defined by the browser.

For example, if you try to access the document object in a Node.js script like this:

console.log(document.getElementById("my-element"));

It will throw an error because the document object is not available in a Node.js environment.

To fix this error, you need to make sure that your code is not trying to access the document object in a non-browser environment, or you can use a library or framework that provides a document-like object in a non-browser environment.

Another potential situation where this error might occur is when you're loading modules and placing them above other scripts that haven't yet loaded.

In this case, you should move the module to the bottom of page (e.g. the last script to be loaded) -

<body>
<!-- main content -->

<!-- module at the bottom -->
<script type="module" src="module.js"></script>
</body>

Checking the runtime environment

There are a few ways you can check whether your JavaScript code is running in a browser or a non-browser environment.

Use the typeof operator to check the type of the window object. In a browser environment, the window object is defined and its type is object, so you can use the following code to check if the code is running in a browser:

if (typeof window === "object") {
  // code is running in a browser environment
} else {
  // code is running in a non-browser environment
}

Use the process.browser property in a Node.js environment. In a Node.js environment, the process.browser property is false, so you can use the following code to check if the code is running in a Node.js environment:

if (process.browser) {
  // code is running in a browser environment
} else {
  // code is running in a Node.js environment
}

Use the navigator.userAgent property. In a browser environment, the navigator.userAgent property contains a string that identifies the browser and its version, so you can use the following code to check if the code is running in a browser:

if (navigator.userAgent) {
  // code is running in a browser environment
} else {
  // code is running in a non-browser environment
}

The specific method you use will depend on your specific needs and your application requirements.