Fix - ReferenceError document is not defined in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Fix - ReferenceError document is not defined #

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).

referenceerror document is not defined

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

Node.js does not provide a browser environment, it's a server side runtime, so we can't use the document variable in Node.

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:

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- Your HTML here --> <!-- 👇️ Script at bottom of body --> <script type="module" src="index.js"></script> </body> </html>

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:

index.js
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 (e.g. in Node.js).

Use the search field on my Home Page to filter through my more than 1,000 articles.