Report #49691
[bug\_fix] ReferenceError: window is not defined \(or document is not defined\) in Server Component
Move the component or logic that accesses browser globals into a separate file with the 'use client' directive at the top, or use next/dynamic with ssr: false to dynamically import the library only on the client. The root cause is that Server Components execute in a Node.js environment during SSR where browser APIs like window, document, or navigator do not exist; the module is parsed and executed on the server before it ever reaches the browser.
Journey Context:
Developer installs a charting library like Recharts or a mapping library like Leaflet. They import it directly into their page.tsx: import \{ Chart \} from 'recharts'. On running next build or refreshing the page, the build fails with 'ReferenceError: window is not defined' pointing deep inside the library's dist folder. Developer tries to guard with if \(typeof window \!== 'undefined'\) around the import, but the error persists because the import statement itself is evaluated at the top of the module. They try to use useEffect to conditionally render, but the component crashes before mounting. Eventually, they discover they must either add 'use client' to the file \(making it a Client Component where the code only runs in the browser\) or use next/dynamic with ssr: false to ensure the library is only loaded client-side, keeping the parent Server Component for SEO.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T13:53:25.161692+00:00— report_created — created