Next.jsMedium

How do you handle browser-only APIs in Server Components?

You cannot use them there. Server Components run on the server, where window, document, localStorage and navigator do not exist. Move the code into a Client Component and access the API in an effect or event handler, or load browser-only libraries with next/dynamic and ssr: false.

Approaches

  1. Client Component + useEffect: effects run only in the browser, after hydration. Initialize state with a safe default and update it in the effect.
  2. Event handlers: code in onClick runs only in the browser.
  3. next/dynamic with ssr: false: skip server rendering for a component entirely. Must be called from a Client Component; it is not allowed in Server Components.
  4. useSyncExternalStore with a server snapshot for values like navigator.onLine or media queries, which avoids hydration mismatches.
  5. Read on the server instead: many "browser" values have server equivalents, such as cookies for theme, headers() for user agent or language, and geo headers from the host.

Avoiding hydration errors

Rendering different output on the server and client (for example localStorage values or Date.now()) causes mismatches. Render a placeholder first and update in an effect, or store the value in a cookie so the server knows it.

With Cache Components

Client Components are also prerendered on the server during SSR. To read synchronous browser-ish values such as Date.now() in a Client Component, React 19.3's use(browser()) or use(io()) (16.3) mark the read so it is deferred out of the static shell.

Guard rail

import "client-only" in modules that touch browser globals makes accidental server imports fail at build time.

Code example

tsx
1// app/components/online-status.tsx
2"use client";
3
4import { useSyncExternalStore } from "react";
5
6function subscribe(cb: () => void) {
7 window.addEventListener("online", cb);
8 window.addEventListener("offline", cb);
9 return () => {
10 window.removeEventListener("online", cb);
11 window.removeEventListener("offline", cb);
12 };
13}
14
15export function OnlineStatus() {
16 const online = useSyncExternalStore(
17 subscribe,
18 () => navigator.onLine, // browser snapshot
19 () => true // server snapshot: avoids hydration mismatch
20 );
21 return <span>{online ? "Online" : "Offline"}</span>;
22}
23
24// Server-side alternative: read what the request already tells you
25// const lang = (await headers()).get("accept-language");

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app