← All fixes
ReferenceError: window is not defined / document is not defined in Next.js (server render)
#137Error
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 yet0 worked0 didn't
Known good on: next@13
Tried it yourself?
Related fixes
next build fails prerendering a page that queries the database
#4Error occurred prerendering page "/leaderboard". Error: DATABASE_URL is not set. Export encountered an error, exiting the build.
Vitest: ReferenceError: describe is not defined
#46ReferenceError: describe is not defined (or it / expect / vi is not defined) when running vitest
vitestjavascriptVerifiedNo reports yet
ReferenceError: require is not defined in ES module scope
#23ReferenceError: require is not defined in ES module scope, you can use import instead
nodeVerifiedNo reports yet