Referenceerror: document is not defined

In this article, we’ll be exploring one specific error called the “Referenceerror: document is not defined” error and diving into its details.

As a JavaScript developer, it’s completely normal to encounter errors while writing code.

These errors actually help us understand what’s wrong with our code and guide us toward finding solutions.

What is Referenceerror: document is not defined?

The “ReferenceError: document is not defined” is a frequent error in JavaScript that arises when attempting to access the “document” object in a non-browser environment, like Node.js.

Wherein the document object is part of the Document Object Model (DOM) and is used to interact with the content of a web page. Thus, it is not available in non-browser environments such as Node.js.

Causes of document is not defined

There are a few situations where you might encounter the “ReferenceError: document is not defined” error:

  • Referencing the document object in Node.js
  • Server-side Rendering (SSR)
  • Typo or incorrect casing

How to fix Referenceerror: document is not defined

To fix the “ReferenceError: document is not defined” error, you need to ensure that your JavaScript code is executed in a browser environment where the “document” object is available.

Here are some specific solutions:

Checking the runtime environment

Particularly, you have a few options to determine whether your JavaScript code is running in a browser or a non-browser environment.

One approach is to utilize 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.”

Thus, you can employ the following code snippet to verify if the code is executing in a browser:

if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {
    // Code is running in a browser environment
} else {
    // Code is running in a non-browser environment
}

Another way is using 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 (typeof process !== 'undefined' && !process.browser) {
    // Code is running in a Node.js environment
} else {
    // Code is running in a browser environment
}

You can also utilize the navigator.userAgent property to determine if the code is running in a browser environment.

In a browser, the navigator.userAgent property holds a string that identifies the specific browser and its version.

By examining this property, you can check if the code is executing in a browser.

Here is an example of how to use this approach:

if (typeof navigator !== 'undefined' && navigator.userAgent) {
    // Code is running in a browser environment
} else {
    // Code is running in a non-browser environment
}

By verifying if the navigator object is defined and the navigator.userAgent property exists, you can conclude that the code is running in a browser environment.

However, if the conditions are not met, it suggests that the code is running in a non-browser environment.

Referencing the document object in Node.js

The document object is a feature specific to web browsers and not a built-in part of JavaScript itself. This means that in environments other than browsers, such as Node.js, the document object is not accessible.

When working with Node.js, you need to be cautious about using browser-specific features like the document object.

If you need to use such features in a code that runs in both the browser and server, you can wrap the code that references the document object inside a conditional statement.

This is to ensure it only runs in the browser.

// This code only runs on the browser

if (typeof document !== 'undefined') {
   let element = document.querySelector('.class-name')
   
   // Manipulating the DOM here
}

Server-side Rendering (SSR)

The “Referenceerror document is not defined” error can also occur when working with static site generators like Nuxt.js, Next.js, or Gatsby.

Another solution, if you are using Next.js, you can utilize the useEffect hook to handle DOM-related code. By placing your code within the useEffect callback, it will run after the component has been mounted and rendered.

Here is an example from React’s documentation:

import { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // DOM-related code goes here
    // This code will only execute on the client-side
  }, []);

  // Rest of your component code
}

By using the useEffect hook with an empty dependency array ([]), you can ensure that the code inside the callback only runs on the client-side.

Typo or incorrect casing

Additionally, it’s important to verify that the document object is written in all lowercase and not capitalized.

// ❌ Wrong
Document.querySelector('.class-name')

// ✅ Correct
document.querySelector('.class-name')

Anyway, here are other fixed errors you can refer to when you might encounter them.

Conclusion

In summary, to resolve the “ReferenceError: document is not defined” error, consider the following:

  • Ensure that you are not attempting to access the document object in a Node.js environment.
  • Verify that you are not using the document object on the server, such as during server-side rendering in frameworks like Next.js.
  • Double-check that you have correctly spelled the document global variable, as it should be written in all lowercase letters.

We hope this guide has assisted you in resolving the error effectively.

Until next time! 😊

Frequently Asked Questions

What is JavaScript ReferenceError and what causes it?

ReferenceError is raised when JavaScript tries to use a variable that doesn’t exist in the current scope. Common causes: typo in variable name, accessing a variable declared with let/const before its declaration (temporal dead zone), assuming Node.js globals exist in the browser (or vice versa), or import path errors in ES modules.

How do I fix ‘window is not defined’ in Next.js or SSR?

Server-side rendering runs your code on the server where ‘window’ (a browser-only global) doesn’t exist. Fix: gate the code with typeof window !== ‘undefined’ OR move it into a useEffect (which only runs client-side). For Next.js, dynamic import with ssr: false also works.

How do I fix ‘fetch is not defined’ in Node.js?

fetch was browser-only until Node 18. Three fixes: (1) Upgrade to Node 18+. (2) Install node-fetch (npm install node-fetch) and import it. (3) Use axios as a cross-platform alternative. For React Native, use the built-in fetch (it’s a browser-like environment).

What is the temporal dead zone in JavaScript?

The period between when a let/const variable is hoisted to the top of its block and when it’s actually declared. Accessing it during this window throws ReferenceError. Example: console.log(x); let x = 5; throws because x hasn’t been declared yet. With var, this would print undefined instead (var is hoisted with undefined value).

Where can I find more ReferenceError fixes?

Browse the ReferenceError reference hub for 34+ specific JavaScript fixes (Node ESM, SSR, React, browser globals). For JavaScript fundamentals see the JavaScript Tutorial hub.

Glay Eliver

Programmer & Technical Writer at PIES IT Solution

Glay Eliver is a programmer and writer at PIES IT Solution, author of over 600 tutorials at itsourcecode.com. Specializes in JavaScript tutorials, Microsoft Office how-tos (Excel, Word, PowerPoint), and Python error debugging covering ImportError, TypeError, AttributeError, ModuleNotFoundError, and JavaScript ReferenceError. Authored several of the site’s highest-traffic Excel and MS Office reference articles.

Expertise: JavaScript · MS Excel · MS Word · MS PowerPoint · Python · Python ImportError · Python TypeError · Python AttributeError · ModuleNotFoundError · JavaScript ReferenceError · Pygame  · View all posts by Glay Eliver →

Leave a Comment