← All errors · Next.js

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

How to fix it

  1. Access browser globals inside useEffect, which only runs in the browser:

    useEffect(() => {
      const saved = window.localStorage.getItem('theme');
    }, []);
  2. Or guard the access:

    if (typeof window !== 'undefined') {
      // browser-only code
    }
  3. For browser-only libraries, load the component with next/dynamic and { ssr: false }.

Related errors

Get new fixes weekly

No spam. Unsubscribe anytime. Privacy