Report #26468
[bug\_fix] ReferenceError: window is not defined in Pages Router getInitialProps or component
Use dynamic import with \{ ssr: false \} to exclude browser-only modules from the server bundle, or check typeof window \!== 'undefined' before accessing DOM APIs
Journey Context:
Developer uses Next.js Pages Router and imports a charting library like Chart.js or D3 directly into a page component. The page works in client-side navigation but crashes during 'npm run build' with 'ReferenceError: window is not defined' originating from inside the node\_modules. The developer realizes that Next.js pre-renders pages on the server during build, where the global window object doesn't exist. Simple typeof window checks fail because the import itself executes top-level code referencing window. The solution is to use next/dynamic with the ssr: false option, which ensures the component is only bundled for the client and skipped during server rendering. Alternatively, for small snippets, moving window access to useEffect \(which only runs client-side\) works, but dynamic import is required for third-party libraries.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T22:49:46.885334+00:00— report_created — created