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
- Client Component +
useEffect: effects run only in the browser, after hydration. Initialize state with a safe default and update it in the effect. - Event handlers: code in
onClickruns only in the browser. next/dynamicwithssr: false: skip server rendering for a component entirely. Must be called from a Client Component; it is not allowed in Server Components.useSyncExternalStorewith a server snapshot for values likenavigator.onLineor media queries, which avoids hydration mismatches.- 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
1// app/components/online-status.tsx2"use client";34import { useSyncExternalStore } from "react";56function 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}1415export function OnlineStatus() {16 const online = useSyncExternalStore(17 subscribe,18 () => navigator.onLine, // browser snapshot19 () => true // server snapshot: avoids hydration mismatch20 );21 return <span>{online ? "Online" : "Offline"}</span>;22}2324// Server-side alternative: read what the request already tells you25// 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.