← All errors · Next.jsReact & Next.js rendering errors
ReferenceError: window is not defined
Exact error
ReferenceError: window is not defined
What it means
Code that touches a browser global (window, document, localStorage) ran on the server during server rendering or build, where those globals don't exist.
Likely causes
- Accessing window/document at the top level of a module or during render.
- Importing a library that assumes a browser at import time.
How to fix it
Access browser globals inside useEffect, which only runs in the browser:
useEffect(() => { const saved = window.localStorage.getItem('theme'); }, []);Or guard the access:
if (typeof window !== 'undefined') { // browser-only code }For browser-only libraries, load the component with next/dynamic and { ssr: false }.
Prevent this next time
- Add ESLint with eslint-config-next (includes the React Hooks rules) and fix warnings before shipping.
- Run `next build` in CI on every pull request so hydration and render errors surface before production.
Guide: catch outages before your users do.
FAQ
What does "ReferenceError: window is not defined" mean?
Code that touches a browser global (window, document, localStorage) ran on the server during server rendering or build, where those globals don't exist.
What usually causes it?
Accessing window/document at the top level of a module or during render. Importing a library that assumes a browser at import time.
How do I fix it?
1. Access browser globals inside useEffect, which only runs in the browser: 2. Or guard the access: 3. For browser-only libraries, load the component with next/dynamic and { ssr: false }.
Related errors
- Hydration failed because the initial UI does not match what was rendered on the server
- You're importing a component that needs useState. It only works in a Client Component
Get new fixes weekly
No spam. Unsubscribe anytime. Privacy