Report #6298
[bug\_fix] window is not defined or document is not defined during Next.js SSR, or 'useState' is called in a Server Component
Add the \`"use client";\` directive as the very first line of the file \(above imports\) to mark the file as a Client Component. This ensures the component only executes in the browser where \`window\`, \`document\`, and React hooks are available. If only a small part of the component uses browser APIs, consider extracting that logic into a separate Client Component and passing data via props from a Server Component, rather than marking the entire file as a client component.
Journey Context:
You create a \`Dashboard.tsx\` component in \`app/dashboard/page.tsx\` \(App Router\). You import \`useState\` and try to access \`localStorage.getItem\('theme'\)\` directly in the component body. On page load, you get a server error: 'localStorage is not defined'. You realize Next.js is rendering this on the server during SSR where browser APIs don't exist. You try to guard it with \`if \(typeof window \!== 'undefined'\)\`, but now you get a different error: 'You're importing a component that needs useState. It only works in a Client Component but one of its parents is...' because you're using React hooks in a Server Component. You finally understand that in the App Router, files are Server Components by default. You add \`"use client";\` as the first line of the file. The errors disappear because Next.js now knows to only run this component in the browser, where both localStorage and React hooks are available.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T23:43:36.195586+00:00— report_created — created