Report #57743
[bug\_fix] ReferenceError: window is not defined or document is not defined during Next.js App Router SSR/build when using browser-only libraries \(e.g., Mapbox, GSAP, charting libraries\) without 'use client' directive.
Add the 'use client' directive as the very first line of the component file \(above all imports\). Root cause: Next.js App Router defaults to Server Components that execute in a Node.js environment where browser globals like window do not exist. The directive forces the component to be bundled and executed only in the browser.
Journey Context:
You install a charting library like Recharts or Mapbox and import it into a component. Everything works in development client-side navigation, but when you run 'next build' or refresh the page, the build fails with 'window is not defined'. You check the stack trace and see it originates from deep within the library's initialization code. You try dynamic imports with ssr: false, which works but feels clunky. Searching the error leads you to Next.js documentation on Client Components. You add 'use client' at the absolute top of your file. The build passes immediately. You realize that without this, Next.js attempted to execute the library's browser-specific code during server-side rendering.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T03:24:43.492219+00:00— report_created — created