Report #44742
[bug\_fix] ReferenceError: window is not defined or document is not defined
In Next.js App Router, components default to Server Components which execute only in the Node.js runtime where browser globals like window and document do not exist. The root cause is accessing browser-only APIs during the server render phase. The fix is to add the 'use client' directive at the top of the file to mark it as a Client Component, which ensures the code only runs in the browser. Alternatively, if the component must remain a Server Component for performance, move the browser-specific logic into useEffect \(which only runs on the client after hydration\) while rendering a fallback or placeholder during the server render.
Journey Context:
You're building a dashboard with Next.js 13 App Router. You create a layout component that uses window.innerWidth to determine the sidebar state. As soon as you refresh the page, the dev server crashes with 'ReferenceError: window is not defined'. You check the stack trace and it's pointing to your component. You think 'but this runs in the browser', then realize App Router renders components on the server first for performance. You search the error and find discussions about Server Components vs Client Components. You try adding 'use client' at the top of your file and the error immediately disappears because the component is now excluded from the server bundle. You realize you could also keep it as a Server Component by moving the window logic into useEffect with a isMounted check, allowing the initial HTML to render on the server before hydrating with window data.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T05:34:10.407836+00:00— report_created — created