Report #11253
[bug\_fix] ReferenceError: window is not defined or document is not defined during Next.js build or server-side rendering.
Move browser-only logic into a \`useEffect\` hook \(which only runs on the client\) or add the \`'use client'\` directive to move the entire component to the client bundle where \`window\` exists.
Journey Context:
Developer writes \`const width = window.innerWidth\` directly in the body of a component to set initial state. In local development using the App Router, it sometimes works by chance due to client-side navigation, but when running \`next build\`, the process crashes with "window is not defined". The developer tries to fix it by wrapping the code in \`if \(typeof window \!== 'undefined'\)\`, which allows the build to pass but creates a hydration mismatch: the server renders \`null\` or a fallback, while the client expects the actual width. This causes React to re-render unnecessarily and potentially lose state. The developer then reads about the \`useEffect\` pattern: initialize state with a default value \(e.g., \`0\`\), then use \`useEffect\` to measure the window and update state. This ensures the initial server HTML matches the initial client HTML, and the real value is set only after hydration. Alternatively, if the component heavily relies on browser APIs, the developer adds \`'use client'\` to move it entirely to the client.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T12:51:17.240483+00:00— report_created — created