AI Workshop: learn to build apps with AI →
Common Errors: "document is not defined" error

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


The error ReferenceError: document is not defined occurs when you try to access the document object in an environment where it doesn’t exist.

Why it happens

The document object is provided by the browser. It’s part of the DOM (Document Object Model) API and represents the web page.

This object is not available in:

  • Node.js
  • Server-side rendering (SSR) environments
  • Server components in frameworks like Next.js

You’re essentially running frontend code in a backend environment.

Fixing in Node.js

In Node.js, there’s no workaround - you must find where document is being used and reconsider why you’re accessing it.

If you need DOM manipulation in Node.js, consider using libraries like:

  • jsdom for simulating a DOM environment
  • cheerio for parsing and manipulating HTML

Fixing in Next.js

In Next.js, your code might run in both situations:

  • Client-side (frontend) when navigating to a page using a link
  • Server-side when using getServerSideProps() or server components

The fix is to wrap browser-specific code in a conditional:

if (typeof window !== 'undefined') {
  // Here `window` is available, so `window.document` (or simply `document`) is available too
}

Using useEffect in React

In React components, you can also use useEffect to ensure code only runs on the client:

import { useEffect } from 'react'

function MyComponent() {
  useEffect(() => {
    // This only runs in the browser
    document.title = 'My Page'
  }, [])
  
  return <div>Hello</div>
}

Dynamic imports

For components that rely heavily on browser APIs, use dynamic imports with ssr: false:

import dynamic from 'next/dynamic'

const ClientOnlyComponent = dynamic(
  () => import('../components/ClientComponent'),
  { ssr: false }
)

This prevents the component from being rendered on the server.

Lessons in this unit:

0: Introduction
1: "X is not a function" errors
2: ▶︎ "document is not defined" error
3: Cannot assign to read only property
4: Parse failure: Unterminated string constant
5: FormData multipart fetch issues
6: regeneratorRuntime is not defined
7: Unexpected identifier in modules
8: Unterminated string literal