Report #7098
[bug\_fix] ReferenceError: window is not defined or document is not defined during SSR/build
Access browser-only globals \(window, document, localStorage, navigator\) only inside useEffect \(which only runs on client\) or after checking typeof window \!== 'undefined'. For third-party libraries that depend on window, import them dynamically with next/dynamic and ssr: false option.
Journey Context:
Developer integrates a charting library \(Chart.js or D3\) into a dashboard. They import it at the top of the component: import Chart from 'chart.js'. The component uses new Chart\(ctx, config\) inside a useEffect. When running next build, the build fails with 'ReferenceError: window is not defined'. Developer realizes that during server-side rendering \(SSR\), the code runs in Node.js where window doesn't exist. They try to guard it with if \(typeof window \!== 'undefined'\) around the import, but ES modules are evaluated at import time. Solution: use next/dynamic to import the component with SSR disabled: const ChartComponent = dynamic\(\(\) => import\('../components/MyChart'\), \{ ssr: false \}\). This ensures the component and its window-dependent library only load in the browser. Alternatively, for simple cases, they can keep the import but only access window inside useEffect, which doesn't run during SSR.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T01:47:37.763776+00:00— report_created — created