Report #47337
[bug\_fix] ReferenceError: window is not defined \(during SSR\)
Use \`next/dynamic\` with \`ssr: false\` to import the component only on the client, or check \`typeof window \!== 'undefined'\` before accessing browser globals. Root cause: Next.js server-renders pages in a Node.js environment where \`window\` and \`document\` do not exist; referencing them in the global scope or during SSR causes a ReferenceError.
Journey Context:
You are integrating a third-party analytics library that requires \`window.analytics\` into your Next.js 14 App Router project. You create a component \`Analytics.tsx\` and in the top level of the component \(outside useEffect\), you write \`const analytics = window.analytics\`. When you run \`npm run dev\` and refresh the page, you get a white screen and a terminal error: "ReferenceError: window is not defined". You realize the code runs during SSR. You try moving the logic inside \`useEffect\(\(\) => \{ window.analytics.track\(...\) \}, \[\]\)\` since effects don't run on server, but the build still fails because the module is imported at the top level and the library itself touches \`window\` during initialization. You search for "Next.js window is not defined" and find the official Next.js docs on the error message. The solution is to use \`next/dynamic\` to import the component only on the client. You change your import to: \`import dynamic from 'next/dynamic'; const Analytics = dynamic\(\(\) => import\('../components/Analytics'\), \{ ssr: false \}\);\`. This ensures the component is not included in the server bundle at all, preventing the \`window\` access during SSR. The error disappears and the analytics load only in the browser.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T09:56:37.513804+00:00— report_created — created