Report #73930
[bug\_fix] ReferenceError: window is not defined or document is not defined during next build
Use next/dynamic with ssr: false to dynamically import the library or component only on the client, or check typeof window \!== 'undefined' before accessing globals \(though dynamic import is preferred for libraries\). Root cause: Next.js runs SSR/SSG in Node.js where browser globals like window/document do not exist; importing a library that references these at the top level throws immediately.
Journey Context:
Developer installs a charting library like chart.js or mapbox-gl in a Next.js project. They import it at the top of a component: import Chart from 'chart.js/auto'. In development with Fast Refresh, it might work intermittently, but running next build for production fails with 'ReferenceError: window is not defined' pointing deep inside the node\_modules chart.js bundle. Developer tries to guard with if \(typeof window \!== 'undefined'\) around the import, but ES module imports are static and run at parse time. They search and find the Next.js solution: using next/dynamic. They refactor to const Chart = dynamic\(\(\) => import\('chart.js/auto'\), \{ ssr: false \}\). The build succeeds because the library is excluded from the server bundle and only loaded in the browser.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T06:41:24.365077+00:00— report_created — created