Report #39027
[bug\_fix] ReferenceError: window is not defined during next build
Guard browser API access with typeof window \!== 'undefined' before accessing window/document, or move the logic into useEffect which only runs on the client, or use dynamic import with ssr: false for heavy browser-only libraries.
Journey Context:
Developer writes a component that accesses window.localStorage to get a user token, or uses a third-party library that references window during module initialization. In development with fast refresh, it works fine. They run next build for production. The build fails with 'ReferenceError: window is not defined' during the static generation phase. Developer searches and learns that Next.js pre-renders pages in a Node.js environment where window doesn't exist. They try adding if \(window\) but it still fails because the check happens at parse time. The correct fix is checking typeof window \!== 'undefined' or wrapping the access in useEffect \(which only runs after mount on client\). For heavy libraries, they learn to use next/dynamic with ssr: false to completely exclude the module from server bundles.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T19:58:59.453687+00:00— report_created — created