Next.js stops with 'document is not defined' while it renders on the server
ReferenceError: document is not definedShort answer
Next.js renders your components on the server first, where there is no document. Find the first file of yours in the stack trace and move the DOM access into a useEffect or an event handler. For a package that touches the DOM on import, load it with next/dynamic and ssr: false from inside a Client Component.
Fix it fast
1Find out which cause you have
Open the stack trace and find the first line that belongs to your project, not to node_modules. Then list every direct use of document in your code to see which file and which kind of component it sits in.
grep -rnE "\bdocument\." app components lib pages src 2>/dev/null2Match what you see, then jump to its fix
- 1
The first project file in the trace is a page, layout or component that has no 'use client' line at the topThe file is a Server ComponentFix - 2
The file starts with 'use client', yet the trace still points at a line where document is used in the component body or at the top of the moduleA Client Component reads document while it rendersFix - 3
The trace points into node_modules, and the import of that package sits in one of your filesA package touches document as soon as it is importedFix
- 1
What does the error look like?
ReferenceError: document is not defined
Cause 1 of 3
The file is a Server Component
1Check
In the App Router every layout and page is a Server Component unless it is marked otherwise, and a Server Component can only run on the server. Browser-only APIs belong in Client Components.
head -n 3 app/page.tsx2Fix
Move the DOM work into a small Client Component and render that from the page. Keep the page itself a Server Component.
// app/ui/page-title.tsx
'use client'
import { useEffect } from 'react'
export default function PageTitle({ title }: { title: string }) {
useEffect(() => {
document.title = title
}, [title])
return null
}3Verify
Start the app and open the page: the error is gone from the terminal and the tab title changes.
npm run devConfirmed by nextjs.org
Cause 2 of 3
A Client Component reads document while it renders
1Check
A Client Component is not only a browser thing. Next.js also uses it to prerender the first HTML on the server, so any document access that is not inside an effect or an event handler runs there too.
grep -n -B2 "document\." components/theme-label.tsx2Fix
Read the DOM inside useEffect, which React runs only on the client, and keep the result in state.
'use client'
import { useEffect, useState } from 'react'
export default function ThemeLabel() {
const [theme, setTheme] = useState<string | null>(null)
useEffect(() => {
setTheme(document.documentElement.dataset.theme ?? 'light')
}, [])
return <span>{theme}</span>
}3Verify
Run a production build; it finishes without the error and the component fills in after the page loads.
npm run buildConfirmed by react.dev
Cause 3 of 3
A package touches document as soon as it is imported
1Check
A package that reads the DOM when its module loads runs that code during server rendering, before any guard in your component can help. An effect cannot fix it, because the import is evaluated first.
grep -rn "import .* from 'the-package-name'" app components src 2>/dev/null2Fix
Load the component lazily with next/dynamic and turn server rendering off for it. Do this in a file that starts with 'use client': ssr: false is rejected in Server Components with the message 'ssr: false is not allowed with next/dynamic in Server Components'.
// app/ui/editor-loader.tsx
'use client'
import dynamic from 'next/dynamic'
const Editor = dynamic(() => import('../../components/editor'), {
ssr: false,
})
export default function EditorLoader() {
return <Editor />
}3Verify
The page renders on the server without the package, and the component appears in the browser after hydration.
npm run build && npm run startConfirmed by nextjs.org
How do I stop it coming back?
- Treat document, window, localStorage and navigator as browser-only: touch them only in effects and event handlers.
- Mark modules that contain browser-only logic with the client-only package, so importing them in the wrong place fails at build time instead of at runtime.
- Read a library's docs for a server-rendering note before you add it to a page.
- Run a production build before each deploy instead of relying on the dev server alone.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- WorkforceA field app, an admin console and a self-hosted Node.js server for push and reconciliation.
Related fixes
Web apps
A Leaflet map crashes the Next.js build or shows up broken
window is not defined
Leaflet reads window as soon as it loads, and Next.js renders Client Components on the server first, where window does not exist.
3 causes, each with a fixWeb apps
React hydration failed: the server HTML and the first browser render differ
Text content does not match server-rendered HTML
Hydration fails when the first render in the browser produces different HTML from the HTML the server sent.
5 causes, each with a fixWeb apps
useState fails in a child component in the Next.js App Router
React client hook in Server Component
In the App Router every component is a Server Component unless a file above it is marked otherwise, and Server Components cannot use state or effects.
3 causes, each with a fixWeb apps
Upgrading to Next.js 16: middleware becomes proxy, and the other things that break
Missing Required default.js for Parallel Route
Next.js 16 renames middleware.ts to proxy.ts and its exported function to proxy.
6 causes, each with a fixWeb apps
Warning: Extra attributes from the server in the console
Text content does not match server-rendered HTML
React found attributes on an element in the server HTML that its own render did not produce.
3 causes, each with a fixWeb apps
A custom error from the server arrives at the client as a generic message
error.digest holds a hash instead of your message
Next.js hides the message of errors thrown in Server Components in production, to avoid leaking details.
3 causes, each with a fix