Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readNext.js
#nextjs#ssr#referenceerror#hydration
Bold white headline reading WINDOW NOT DEFINED with a Next.js server crate and a cyan browser window icon behind a locked amber gate.

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:

code
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.

tsx
"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:

ts
// 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
tsx
// 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 runsWhen it runsWhat is available
Server component renderbuild + requestprocess.env, fetch, Node APIs
Client component renderbuild + request + browserno window during the server pass
Effect in a client componentbrowser only, after paintwindow, document
Event handlerbrowser only, after interactionwindow, document
Route handler or server actionrequest onlyno 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:

TechniqueRuns on the server firstAllowed in a server componentReplaces the whole module
useEffectrenders fallback markupno, needs "use client"no
Event handlernonono
typeof window !== "undefined"yes, returns falseyesno
next/dynamic with ssr: falsenono, client onlyyes
await import() inside an effectnonoyes, lazily
dynamic = "force-dynamic"yes, per requestyesno, only skips prerender

The same problem, ordered by how often it appears in the wild:

SymptomReal causeFix
build fails, no browser involvedmodule-scope window reached by an importmove it into an effect or guard the module
works locally, fails on Vercellocal dev skipped prerender for that routerun next build before pushing
window is not defined inside a librarylibrary reads document on importnext/dynamic with ssr: false
renders twice, hydration warningserver HTML differs from client HTMLrender null until mounted

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. The module scope is the trap, the call site is not

ts
// 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:

tsx
"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:

tsx
"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:

ts
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:

tsx
// 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:

tsx
"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 documentation

The Next.js documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.