Report #65393
[bug\_fix] ReferenceError: window is not defined or document is not defined during Next.js build or server-side render
Move the browser-only code inside useEffect \(which only runs on client\), or use dynamic import with ssr: false, or check typeof window \!== 'undefined' before accessing the API
Journey Context:
Developer writes a utility that accesses localStorage directly at the module level or in component render. Everything works in development \(client-side navigation\), but production build \(npm run build\) crashes with window is not defined. Developer confused because it worked in dev. Realizes Next.js pre-renders pages at build time in Node.js where window doesn't exist. Tries adding a check typeof window \!== 'undefined' which fixes the build but causes the component to render nothing on server then suddenly appear on client \(flicker\). Better fix: useEffect runs only after component mounts on client, so window access is safe there. Dynamic import with ssr: false is the nuclear option for heavy browser-only libraries.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T16:14:33.812394+00:00— report_created — created