Document Is Not Defined in JavaScript

The “ReferenceError: document is not defined” error occurs for multiple reasons:

  1. Using document in Node.js.
  2. Using document on the server (e.g. server side rendering in Next.js).
  3. Misspelled the document global variable (should be all lowercase).

The document relates to the document object, which represents a web page that is loaded in the browser.

Node.js, however, is not a browser environment. It is a server environment, much like PHP or Perl, and as such, you can’t access the browser’s DOM or do anything specific to browser-hosted JavaScript.

If you are experiencing the “ReferenceError: document is not defined” error in the browser, try to move your JS script tag to the bottom of the body tag:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />

    <!-- Your HTML here -->

    <!-- 👇️ Script at bottom of body -->
    <script type="module" src="index.js"></script>

You might have some addons that are ran before the DOM is created.

If you’re using Next.js and you need to check if you’re on the browser (can use document) or on the server (can’t use document), you can do this in the following way:

if (typeof window !== 'undefined') {
  console.log('You are on the browser')
} else {
  console.log('You are on the server')

We check if the global window variable does not have a type of undefined. If the window global is defined, we are on the browser and can use the document variable.

To solve the”ReferenceError: document is not defined” error, make sure to only use the document global variable on the browser. The variable relates to the Document Object Model, which represents a web page that is loaded in the browser and can’t be used on the server side.

Recommended Articles