Report #104505
[bug\_fix] ReferenceError: window is not defined \(during SSR in Server Components\)
Move browser-only code \(e.g., accessing \`window\`, \`document\`, \`localStorage\`\) into a \`useEffect\` inside a Client Component, or use dynamic import with \`ssr: false\`. The root cause is that Server Components run on the server where browser globals do not exist; attempting to use them directly causes a runtime error.
Journey Context:
I was building a Next.js 14 app with a component that checks \`window.innerWidth\` to conditionally render a mobile menu. I used \`const width = window.innerWidth;\` directly in the component. The build succeeded but the page crashed on load with 'ReferenceError: window is not defined'. I was confused because it worked in development \(which sometimes runs client-side only\). The error only appeared during SSR. I learned that all components are Server Components by default and run on the server. The fix was to convert the component to a Client Component by adding \`'use client'\` and then moving the \`window\` access inside a \`useEffect\` \(or using a custom hook like \`useWindowSize\`\). Alternatively, I could use \`next/dynamic\` with \`\{ ssr: false \}\` to load the component only on the client. I implemented the \`useEffect\` approach and it worked.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-08-30T20:03:53.662852+00:00— report_created — created