Next.js: ReferenceError: document is not defined
Code used the DOM (document) while rendering on the server.
ReferenceError: document is not defineddocument is not defined Next.js SSRReferenceError: document is not defined at createPortalError occurred prerendering page document is not defined Meaning
Same cause as window is not defined: DOM APIs exist only in the browser. Use refs and useEffect, portals created after mount, or dynamic(..., { ssr: false }) for DOM-heavy libraries (editors, charts). For createPortal(document.body) wait until mounted.
Common causes
document.getElementByIdduring render- Portal using
document.bodyon the server - Libraries touching
documentat import - SSR of a component meant for the client
- Script injection code at module level
⚡ Quick fix
- Move DOM code into
useEffect - Mount flag:
const [mounted,setMounted]=useState(false)before portals - Dynamic import with
ssr: false
Detailed fix by platform
Next.js
useEffect(() => { document.title = "Hello"; }, []);
How to diagnose
- Code — Render or effect?
- Portal — Mounted guard?
- Lib — SSR-safe?
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
- [Vue warn]: Hydration node/text/children mismatch Vue: [Vue warn]: Hydration text content mismatch / Hydration node mismatch: server rendered element contains more child nodes than client vdom
- Conflicting app and page file was found Next.js: ⨯ Conflicting app and page file was found, please remove the conflicting files to continue: "pages/index.tsx" - "app/page.tsx"
- Hydration failed Error: Hydration failed because the initial UI does not match what was rendered on the server
Most viewed in Next.js
- NEXT_REDIRECT Next.js: Error: NEXT_REDIRECT (redirect() inside try/catch)
- server-only Next.js: You're importing a component that needs "server-only". That only works in a Server Component
- cookies() should be awaited Next.js 15: Route "/x" used `cookies().get('token')`. `cookies()` should be awaited before using its value
Other ways to find it
Where this error sits
Origin: On your device. Errors that are often confused with or caused by this one (click to open):
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 5 Nov 2026