Report #49167
[bug\_fix] ReferenceError: window is not defined or document is not defined in Server Component
The root cause is that Next.js App Router Server Components execute in a Node.js environment during server-side rendering or static generation, where browser globals like window, document, and navigator do not exist. The fix is to move the browser-specific code into a Client Component \(marked with 'use client'\), or use next/dynamic with ssr: false for heavy libraries, or gate the code with typeof window \!== 'undefined' \(though this effectively makes it client-only and should preferably be in a Client Component\).
Journey Context:
Developer migrates a charting library \(e.g., Chart.js or Recharts\) into an App Router page. They import the library at the top of a Server Component file. Immediately upon running the dev server, they get 'ReferenceError: window is not defined' during the SSR phase. They try wrapping the usage in if \(typeof window \!== 'undefined'\) but the error persists because the import itself evaluates the library's top-level code. They search for solutions and find the 'use client' directive. They create a separate Chart.tsx file with 'use client', move the library import there, and import that component into the Server Component. The error disappears and the chart renders client-side. They understand that Server Components cannot access the DOM.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T13:00:25.479603+00:00— report_created — created