ReferenceError: window is not defined (Next.js)
ReferenceError: window is not definedIn one sentence: Code that only works in a browser (window, document, localStorage) ran on the server, where those don't exist.
What it means
Next.js renders pages on the server first, in Node.js. Node has no browser, so `window`, `document`, `localStorage` and `navigator` are undefined there. When any code touches them while the page is being rendered on the server, you get this error.
It often shows up after an AI tool adds a chart, map, editor or analytics library, because many of those read `window` as soon as they are imported.
Common causes
- Reading `window` or `localStorage` directly in the component body instead of inside `useEffect` or an event handler.
- Importing a browser-only library (maps, charts, rich text editors, some animation libraries) at the top of a server-rendered page.
- Using `window` in a Server Component, or in a file that a Server Component imports.
How to fix it
- Move browser-only code into `useEffect`, which only runs in the browser after the page loads.
- If you need the value during render, guard it: `typeof window !== "undefined" ? window.innerWidth : 0`, and expect the first render to use the fallback.
- Load browser-only libraries with `next/dynamic` and `ssr: false` from a Client Component, so they never run on the server.
- Make sure the component that uses them starts with `"use client"`.
Before
const theme = localStorage.getItem("theme"); // crashes on the serverAfter
"use client";
import { useEffect, useState } from "react";
const [theme, setTheme] = useState("light");
useEffect(() => {
setTheme(localStorage.getItem("theme") ?? "light");
}, []);Prompt to paste into your AI tool
My Next.js app crashes with 'window is not defined'. Move every use of window, document and localStorage into useEffect or event handlers, load browser-only libraries with next/dynamic and ssr: false, and don't change unrelated code.Still stuck?
Paste your exact error and code. Get a plain-English explanation free, or the full fix for $5.
Related errors
- TypeError: Cannot read properties of undefined
- CORS error: blocked by CORS policy
- Hydration failed: server HTML didn't match the client (Next.js)
- Module not found: Can't resolve '...'
Weekly: the errors breaking vibe-coded apps and how to fix them. Free.
No spam. Unsubscribe anytime.