Next.jsReact

ReferenceError: window is not defined

ReferenceError: window is not defined

In short: Server-side rendering ran code that touches window, document, or localStorage. Those exist only in the browser.

Why it happens

Next.js and other SSR tools run your component first on the server, where there is no browser global. This often appears after an AI tool adds window.localStorage, document.getElementById, or a browser-only library at the top of a file, or reads window during render in a Server Component. It is a crash during the server render, not the same thing as a hydration mismatch (which happens later, when the server HTML and the client HTML differ).

How to fix it

  1. Find the first stack-trace line that references window, document, localStorage, or a library that uses them.
  2. If you only need the value in the browser, move the read into a useEffect (or an event handler) in a Client Component, and render a placeholder on the first paint.
  3. Don't read browser globals at module top level (outside a function). That runs as soon as the file is imported, including on the server.
  4. For a component that cannot work without the DOM (a map widget, a rich text editor), load it with next/dynamic and ssr: false, on that component only.
  5. Guard leftover checks with typeof window !== "undefined" so the server skips them.

Example

"use client";
import { useEffect, useState } from "react";

export function ViewportWidth() {
  const [width, setWidth] = useState<number | null>(null);
  useEffect(() => { setWidth(window.innerWidth); }, []);
  return <span>{width ?? "…"}</span>;
}
Don't: Don't turn the whole app or layout into a client-only dynamic import just to hide this error. You lose server rendering for everything under it.

Copy-paste fix prompt

3 · The fix promptPaste into Cursor, Claude Code, Codex, Lovable, Bolt, Replit or v0
I'm getting this error in my app:

ReferenceError: window is not defined

[Paste the full error, stack trace, and the file it points to here]

Likely cause: Server-side rendering ran code that touches window, document, or localStorage. Those exist only in the browser.

Task: Find every window, document, localStorage, or browser-only library access that runs during server render or at module top level. Move those into useEffect or a dynamic import with ssr:false on the smallest component that needs them.

Rules:
- First explain the root cause in 2 sentences and list the files you'll change.
- Make the smallest change that fixes it. Don't refactor unrelated code.
- Don't disable security or checks (RLS, auth, signature verification, type checking, CORS allow-all) to make the error disappear.
- Never print or hard-code secret keys.
- Finish by telling me exactly how to verify the fix.

Common with: Cursor, v0, Claude Code, Bolt. Last reviewed 2026-11-15.

Related fixes

← All fixes · Still stuck? Use the diagnose-first prompt