Referenceerror document is not defined node js – How to Fix ReferenceError document is not defined in JavaScript?

Referenceerror document is not defined node js: The “ReferenceError: document is not defined” error can occur for a variety of factors, including:

  • When you use the document in Node.js.
  • While using the document on the server (example:- server-side rendering in Next.js).
  • When misspelled the document global variable (must be all lowercase).

NOTE:

Because Node.js is a server-side runtime and does not provide a browser environment, 
we cannot use the document variable in Node.

Fixing the ReferenceError: document is not defined

Document not defined javascript: If your browser displays the “ReferenceError: document is not defined” issue, try moving your JavaScrpit script tag to the bottom of the body tag as shown below:

index.html:

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

  <body>
     <!-- write your HTML here -->
     <p>Hello this is Btechgeeks</p>

    <!-- adding type as module in the script   -->
    <script type="module" src="index.js"></script>
  </body>
</html>

Output:

Hello this is Btechgeeks

In our JavaScript code, we can now use the syntax of the ES6 module.
It’s important to remember that any JavaScript files that use the syntax of the ES6 module must have the type attribute set to the module.

You may have add-ons that are executed before the DOM is created.

If you’re using Next.js and want to know if you’re in the browser (can use document) or on the server (can’t use document), you can do so as follows:

index.js: (for undefined)

// Check if the type of window is not equal to 'undefined' using 
// the if conditional statement 
if (typeof window !== 'undefined') {
  // If it is true then print 'we are on the browser'
  console.log('Hey!!! we are on the browser')
} else {
  // Else print ' we are on the server'
  console.log('Hey!! we are on the server')
}

Output:

Hey!! we are on the server

Explanation:

  • Here we checked if the global window variable does not have a type of ‘undefined’.
  • We are on the browser if the window global is defined, and we can use the document variable.

If we write the same code in the browser then the type of window returns an object.

Input:

console.log(typeof window)

Output:

object

Handling ReferenceError: document is not defined in JS

Referenceerror document is not defined: To fix the “ReferenceError: document is not defined” error, simply use the document global variable on the browser.

The variable is related to the Document Object Model, which represents a browser-loaded web page that cannot be utilized on the server-side (for example -in Node.js).