Report #84198
[bug\_fix] ReferenceError: window is not defined or document is not defined during Next.js SSR build or server-side rendering, occurring when importing libraries that assume browser environment \(Chart.js, D3, Leaflet\) or accessing browser globals during module initialization.
For components using browser APIs, add the 'use client' directive at the top of the file. For third-party libraries that access window during import, use next/dynamic with ssr: false to ensure the library is only loaded on the client. Root cause: Next.js executes code on the server during SSG/SSR where browser globals don't exist.
Journey Context:
You're integrating a charting library into your Next.js dashboard. You import it at the top of your component: \`import Chart from 'chart.js/auto'\`. The moment you run \`next build\`, the build crashes with 'window is not defined'. You check your component and see that you're only using the Chart inside useEffect, which should only run on the client. You realize that the crash happens at import time—the library's entry point immediately accesses \`window\` when the module loads. You try conditional imports with \`if \(typeof window \!== 'undefined'\)\` but get React hooks errors because the hook calls become conditional. You search Next.js patterns and find the dynamic import solution with \`ssr: false\`. You refactor to use \`const Chart = dynamic\(\(\) => import\('chart.js/auto'\), \{ ssr: false \}\)\`. Alternatively, if the entire component is client-only, you move it to a file with 'use client' and ensure no server APIs are used. The build succeeds because Next.js knows to exclude this code from the server bundle.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T23:54:58.857507+00:00— report_created — created