Yarrow
← All fixes

ReferenceError: window is not defined / document is not defined in Next.js (server render)

#137
nextjsreactjavascriptshared by unknownNov 17, 2026

Error

ReferenceError: window is not defined (or document / localStorage / navigator is not defined) during next build or on page load

Why it happens, and why this works

Next.js renders components on the server first (in Node), where window and document don't exist, and 'use client' components are still pre-rendered on the server. useEffect and ssr:false code only runs in the browser, so the globals exist by then.

Fix

Only touch browser globals after the component mounts in the browser.
1. Move the access into useEffect: useEffect(() => { const w = window.innerWidth; ... }, []) and mark the file 'use client'.
2. For a library that touches window at import time, load it client-only: const Map = dynamic(() => import('./Map'), { ssr: false }) (in App Router this dynamic() call must itself be inside a Client Component).
3. For one-off checks outside React: if (typeof window !== 'undefined') { ... }
Don't read window in the render body to pick initial state, that also causes hydration mismatches; read it in useEffect and set state.

Did it work?

No reports yet
0 worked0 didn't

Known good on: next@13

Tried it yourself?

Related fixes