Next.js: ReferenceError: window is not defined during render
window is not defined means browser code ran on the server. Effects, client-only dynamic imports and guarded modules each fix a different layer.

Introduction & Quick Summary
Next.js renders every route on the server before the browser ever sees it, so a module that touches window at import time fails there:
ReferenceError: window is not defined
at Object.<anonymous> (/app/.next/server/chunks/1234.js:1:2345)
at require (/app/node_modules/next/dist/compiled/...)Quick answer: keep browser globals inside an effect, or load the module only on the client.
"use client";
import { useEffect, useState } from "react";
export function ScreenWidth() {
const [width, setWidth] = useState<number | null>(null);
useEffect(() => {
const onResize = () => setWidth(window.innerWidth);
onResize();
window.addEventListener("resize", onResize);
return () => window.removeEventListener("resize", onResize);
}, []);
return <span>{width ?? "…"}</span>;
}There is no single bug called "window is not defined". There are four different places the same line can run, and each has its own fix. Confusing them is what turns a two-line change into an afternoon of guessing, because a typeof window !== "undefined" check fixes one of the four and breaks the other three.
Core Mechanics, Signatures & Reproducible Setup
In the App Router, a page is a server component by default. Its module graph is evaluated in Node during next build (for static routes) and again per request (for dynamic routes). "use client" does not disable that: a client component is still server-rendered to HTML first, then hydrated. So window is unavailable in both components during the first pass.
Reproduce it with one shared module:
// lib/tracker.ts
export const start = () => console.log(window.location.href);
export const runtime = typeof window === "undefined" ? "server" : "client";
const saved = window.localStorage.getItem("theme"); // evaluated on import// app/page.tsx (server component)
import { runtime } from "@/lib/tracker";
export default function Page() {
return <p>{runtime}</p>;
}next build fails while collecting page data, and the stack points at the generated server chunk rather than your source. The giveaway is the phrase "Error occurred prerendering page" or "Export encountered errors on following paths" above the ReferenceError.
| Where the line runs | When it runs | What is available |
|---|---|---|
| Server component render | build + request | process.env, fetch, Node APIs |
| Client component render | build + request + browser | no window during the server pass |
| Effect in a client component | browser only, after paint | window, document |
| Event handler | browser only, after interaction | window, document |
| Route handler or server action | request only | no DOM at all |
That table is the whole diagnosis. If a line touches window, it belongs in row three or four, never in row one or two.
Key Comparison Table
Ways to reach browser-only code, and where each one is legal:
| Technique | Runs on the server first | Allowed in a server component | Replaces the whole module |
|---|---|---|---|
useEffect | renders fallback markup | no, needs "use client" | no |
| Event handler | no | no | no |
typeof window !== "undefined" | yes, returns false | yes | no |
next/dynamic with ssr: false | no | no, client only | yes |
await import() inside an effect | no | no | yes, lazily |
dynamic = "force-dynamic" | yes, per request | yes | no, only skips prerender |
The same problem, ordered by how often it appears in the wild:
| Symptom | Real cause | Fix |
|---|---|---|
| build fails, no browser involved | module-scope window reached by an import | move it into an effect or guard the module |
| works locally, fails on Vercel | local dev skipped prerender for that route | run next build before pushing |
window is not defined inside a library | library reads document on import | next/dynamic with ssr: false |
| renders twice, hydration warning | server HTML differs from client HTML | render null until mounted |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. The module scope is the trap, the call site is not
// bad: evaluated once per server process, throws immediately
const isMobile = window.matchMedia("(max-width: 768px)").matches;
// safe: evaluated lazily, and only in the browser
export function isMobile() {
if (typeof window === "undefined") return false;
return window.matchMedia("(max-width: 768px)").matches;
}A top-level const that reads window executes on import, which happens during the server pass no matter which component imports the file. Wrapping the function body is what fixes it; guarding the import is the other option.
2. Effects, layout effects and the rule behind them
useEffect and useLayoutEffect only run in the browser, and useLayoutEffect additionally warns during server rendering. That makes an effect the default home for anything touching document:
"use client";
import { useEffect, useRef } from "react";
export function FocusOnMount({ children }: { children: React.ReactNode }) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
ref.current?.querySelector<HTMLInputElement>("input")?.focus();
}, []);
return <div ref={ref}>{children}</div>;
}Effects never run during prerender, so this code is safe in a static page. What is not safe is computing the value during render and then "fixing" it in an effect: the server-rendered HTML then differs from the first client render, and React reports a hydration mismatch instead.
3. Third-party libraries that expect a browser
Chart, map and editor packages touch document at import time. next/dynamic with ssr: false removes them from the server graph:
"use client";
import dynamic from "next/dynamic";
const Chart = dynamic(() => import("recharts").then((m) => m.LineChart), {
ssr: false,
loading: () => <div className="h-64 animate-pulse rounded bg-slate-800" />,
});
export function Revenue({ data }: { data: { day: string; total: number }[] }) {
return <Chart width={640} height={256} data={data} />;
}Two rules make this reliable. ssr: false is only allowed inside a client component, so the file that calls dynamic must start with "use client". And the wrapping module must stay small: importing the library directly anywhere still pulls it into the server bundle.
4. typeof window guards: useful, frequently misused
A guard is correct when the same expression must produce a different value on each side and the difference does not affect markup. It is wrong when it hides a real feature split:
export const apiBase =
typeof window === "undefined" ? process.env.INTERNAL_API : "/api";Here the server talks to an internal address and the browser uses a relative path, and the output is a value, not markup, so nothing mismatches. Compare with this, which produces different HTML on each side and triggers a hydration error:
// bad
return <p>{typeof window === "undefined" ? "loading" : localStorage.getItem("user")}</p>;process.browser was removed from Next.js long ago; do not bring it back.
5. localStorage, cookies and media queries at render time
Persisted client state has to arrive after mount, because the server cannot know it. The mounted-flag pattern keeps you out of hydration trouble:
"use client";
import { useEffect, useState } from "react";
export function useStored<T>(key: string, fallback: T) {
const [value, setValue] = useState<T>(fallback);
const [ready, setReady] = useState(false);
useEffect(() => {
const raw = window.localStorage.getItem(key);
if (raw !== null) setValue(JSON.parse(raw) as T);
setReady(true);
}, [key]);
return [value, ready, setValue] as const;
}Render a skeleton while ready is false. If the value is genuinely needed during the first paint, the honest answer is a cookie read on the server, not a browser read during render. The same reasoning covers navigator.language, matchMedia and document.documentElement.dataset.
6. The failure at build time, not at runtime
When the error is prefixed with "Error occurred prerendering page /blog/[slug]", the route was statically rendered and one of its imports touched window. Three responses, in order of preference: move the code into an effect; extract the browser part into a client component loaded with ssr: false; or opt the route out of prerendering with export const dynamic = "force-dynamic". The last one costs a full render per request and should be a deliberate trade, not a reflex.
A malformed response body is easy to spot with the cURL builder before blaming the front end, and a global constructor pattern such as window.location.href.replace(/.../, "") can be rehearsed in the regex tester instead of reloading the page.
Common Compilation/Runtime Mistakes & Version Gotchas
Believing "use client" means "browser only". It marks the boundary where the client bundle starts; the component is still rendered to HTML on the server. Anything that assumes window exists needs an effect regardless of the directive.
Guarding the call but not the import. if (typeof window !== "undefined") import("leaflet") still evaluates the outer module. Use next/dynamic or a useEffect import.
Rendering a different tree on the first client pass. A guard that changes markup produces "Text content does not match server-rendered HTML" or React error 418. Render the same fallback on both sides and update after mount.
Version notes. Next.js 13 introduced the App Router with React Server Components as the default. Next.js 15 made params and searchParams promises, which changed when route data is read but not when browser globals become available. Next.js 16 moved caching to the cacheComponents model, so a route that used to be static may prerender at build time again after an upgrade — the classic way an old window bug comes back.
next/dynamic with ssr: false has been unsupported in server components since the App Router shipped, so check the directive first when it refuses to compile.
Reference material: Server and Client Components and Lazy loading.
Official references
primary documentationThe Next.js documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesModule not found: Can't resolve a package or alias in Next.js
TypeScript and the bundler resolve imports separately. Align path aliases, workspace dependencies, exports conditions and filename case.
Next.js 16 DynamicServerError: cookies(), headers() and fetchCache
Request-time APIs make a route dynamic, and Next 16 replaced the segment configs with Suspense boundaries and use cache. What to delete and what to wrap.
Next.js cacheComponents: 'used uncached or runtime data' build error
Cache Components makes the build refuse to guess where the static shell ends. Stream it, cache it with use cache, or declare the route blocking.
next/font: Failed to fetch a Google font during the build
The font is fetched during the build, not at runtime. Vendor it with next/font/local or give CI and Docker a route out.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.