Report #24084
[bug\_fix] ReferenceError: window is not defined or ReferenceError: document is not defined during npm run build
Move browser-only code inside useEffect with empty dependency array \(runs only on client\), or use next/dynamic with ssr: false to exclude the entire component from server rendering.
Journey Context:
Developer writes a component that accesses window.localStorage or document at the top level of the module or during the render phase. The code works fine in development mode with client-side navigation, but crashes during next build with 'window is not defined'. The developer initially tries wrapping the code in typeof window \!== 'undefined' checks, but in Next.js App Router this can still fail during the server render phase. The root cause is that Next.js pre-renders pages on the server during build, where browser APIs do not exist. The fix requires moving any window/document access into useEffect, which only executes after the component mounts on the client, or using dynamic imports with ssr: false to completely prevent the component from being included in the server bundle.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T18:50:18.510298+00:00— report_created — created