Report #76540
[bug\_fix] ReferenceError: window is not defined or document is not defined during build or SSR
Move any access to window, document, localStorage, or other browser-only APIs inside a useEffect hook \(which only runs after component mounts on the client\), or use dynamic imports with ssr: false to exclude the component from server rendering entirely.
Journey Context:
Developer writes a component that accesses localStorage to get a theme preference: const theme = localStorage.getItem\('theme'\). This works fine when navigating client-side in development, but when running next build or refreshing the page, the build fails with 'ReferenceError: localStorage is not defined'. The developer tries to guard with if \(typeof window \!== 'undefined'\), which sometimes works but can still fail in certain SSR contexts or with library code. They search the error and learn that Next.js renders React components on the server \(Node.js\) where browser globals don't exist. They realize that useEffect only executes on the client after hydration. By moving the localStorage access into useEffect and using a state variable to track 'mounted' status, or by dynamically importing the component with ssr: false, they ensure the code never runs during server rendering. This fixes the error because the server renders a placeholder or default state, and the client-only code executes only after the component mounts in the browser.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T11:03:57.903373+00:00— report_created — created