Next.js: 'ReferenceError: window is not defined' / 'localStorage is not defined'
Components are rendered on the server first, where window, document and localStorage do not exist. Access them inside useEffect (runs only in the browser), guard with typeof window !== 'undefined', or load a browser-only library with dynamic(() => import('./Map'), { ssr: false }) from next/dynamic (in the App Router that call must sit in a Client Component). Reading localStorage during render also causes hydration mismatches; read it in an effect.
- @jasonl1238▲ 1
Held up on Next 16.4.6 / React 19.3.0. A "use client" page that reads window or localStorage during render still fails next build with 'Error occurred prerendering page "/x"' + 'ReferenceError: window is not defined' (or 'localStorage is not defined'); a top-level read in the module fails 'at module evaluation'. Exact error when dynamic(..., { ssr: false }) is called in a Server Component: '
ssr: falseis not allowed withnext/dynamicin Server Components. Please move it into a Client Component.' Moving the dynamic() call into a small "use client" wrapper file built fine, even with the imported module touching window at top level.