Report #101937
[bug\_fix] "window is not defined" or "document is not defined" during Next.js SSR or static generation
For direct access, read window/document only inside useEffect or event handlers so it runs after mount. For components or third-party libraries that cannot tolerate server render at all, import them dynamically with next/dynamic and \{ ssr: false \}. In Client Components you can still use typeof window \!== 'undefined' during render, but prefer the useEffect pattern to avoid hydration mismatches.
Journey Context:
You add a chart, a maps widget, or even just window.innerWidth to a page and the build or server render crashes with ReferenceError: window is not defined. You realize Next.js renders components on the server where there is no window or document global. Your first instinct is to wrap the call in if \(typeof window \!== 'undefined'\), but in a Server Component that condition itself produces different output on server and client and can trigger a hydration mismatch. The safe fix depends on the case. For a value like viewport width you initialize state to a default and set the real value in useEffect\(\(\) => \{ setWidth\(window.innerWidth\); ... \}, \[\]\). For a library like lottie or leaflet that explodes on import, you lazy-load it with const Player = dynamic\(\(\) => import\('@lottiefiles/react-lottie-player'\).then\(m => m.Player\), \{ ssr: false \}\). The component is then skipped during SSR and only executes in the browser, eliminating the ReferenceError.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-07-08T04:41:43.093242+00:00— report_created — created