Report #78492
[bug\_fix] \`window is not defined\` or \`document is not defined\` during Next.js build or SSR in App Router
Add the \`"use client"\` directive at the very top of the file \(before any imports\) to mark the file as a Client Component where browser APIs are safe. Alternatively, for heavy browser-only libraries, use \`next/dynamic\` with \`ssr: false\`, or guard access with \`typeof window \!== 'undefined'\` inside \`useEffect\`.
Journey Context:
Developer migrates a landing page from Pages Router to App Router. They import a third-party analytics library that internally accesses \`window.ga\` at the module level \(top scope\). In \`page.tsx\`, they import and initialize it. Immediately upon running \`next build\`, the process crashes with 'ReferenceError: window is not defined'. The developer understands that App Router uses Server Components by default, which execute in a Node.js environment without a \`window\` object. They try moving the initialization into a \`useEffect\`, but the error persists because the module is still imported \(and thus evaluated\) on the server during the server component render. They consider using \`next/dynamic\` but need the analytics to be synchronous with the page load. Finally, they discover the \`"use client"\` directive: by adding it to the top of the file, the entire file is marked as a Client Component. This forces Next.js to only render this file in the browser, where \`window\` is defined, resolving the build error.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T14:20:54.283299+00:00— report_created — created