Lesson 3 of 27Foundations
Server and Client Components
Decide what runs on the server and what ships to the browser, and compose the two without leaking code or secrets.
Rendering Strategies asked where and when a page's HTML is made. This lesson asks the same question about each component inside the page. It is the biggest mental shift in modern Next.js, and the topic interviewers probe hardest. Where a component runs decides how much JavaScript your users download, whether a secret can leak, and whether a hook is even allowed. Once the boundary clicks, most "why does this error?" moments in the App Router make sense.
Server Components are the default
Every component in app/ is a Server Component unless you say otherwise. A Server Component runs only on the server, during the build or a request. Its code never reaches the browser. Three things follow:
- It can be
asyncandawaitdata directly. NouseEffect, no loading state juggling. - It can use secrets and server-only libraries (database clients, API keys, the file system) safely.
- It adds zero JavaScript to the client bundle. A page that only renders a list ships no code for that list.
import { db } from "@/db";
export default async function ProductsPage() {
const products = await db.query.products.findMany({ limit: 20 }); // runs on the server
return (
<ul>
{products.map((p) => (
<li key={p.id}>
{p.name}: ${p.price}
</li>
))}
</ul>
);
}What Server Components cannot do is anything that needs the browser at runtime: useState, useEffect, useReducer, context, event handlers like onClick, or browser APIs like window and localStorage. They render once on the server and are done.
const [open, setOpen] = useState(false) to a component in app/products/page.tsx with no directive at the top. What happens?The "use client" boundary
To make a component interactive, put the "use client" directive at the very top of its file, above the imports:
"use client";
import { useState } from "react";
export function AddToCart({ productId }: { productId: string }) {
const [added, setAdded] = useState(false);
return (
<button onClick={() => setAdded(true)} disabled={added}>
{added ? "Added" : "Add to cart"}
</button>
);
}A Client Component is still rendered to HTML on the server for the first load (so users see it immediately), then its JavaScript is downloaded and hydrated in the browser: React attaches the event handlers and state to that HTML.
The directive marks a boundary in the module graph, not just one component. Once a file is marked "use client", every module it imports and every component it renders directly becomes part of the client bundle too. You only need the directive at the entry point of each interactive island.
Everything is a Server Component by default. On its own, this page would ship no component JavaScript.
Push the boundary as far down the tree as you can. Marking the whole layout "use client" because one search box needs state would ship the logo, navigation and everything else they import.
Server Component or Client Component?
How the two kinds of component meet
On a first page load, the work splits like this:
Put the first page load of a mixed page in order.
- Tap the steps below in the right order.
On later navigations, the browser fetches only the RSC payload for the new route, and Client Components render entirely in the browser.
Passing data across the boundary
A Server Component can render a Client Component and pass it props. Those props travel inside the RSC payload, so they must be serialisable by React: strings, numbers, booleans, null, plain objects, arrays, Date, Map, Set, Promises, and JSX. Regular functions and class instances cannot cross. (The exception is a Server Function, a function marked "use server", which you will meet in the server actions lesson.)
import { getProduct } from "@/lib/products";
import { AddToCart } from "../_components/AddToCart";
export default async function ProductPage(props: PageProps<"/products/[id]">) {
const { id } = await props.params;
const product = await getProduct(id);
return (
<>
<h1>{product.name}</h1>
<AddToCart productId={product.id} /> {/* a string: fine */}
{/* <AddToCart onAdd={() => log(id)} /> a function: error */}
</>
);
}Here is a rough version of that rule as code. Run it and see which props would be rejected.
Press Run (⌘ Enter) to see what happens.What does this print?
const props = { title: "Mug", sizes: ["S", "M"], format: (n: number) => n.toFixed(2) };
const bad = Object.entries(props).filter(([, v]) => typeof v === "function").map(([k]) => k);
console.log(bad.join(","));Composition: server content inside client components
What if a Client Component (say, a modal with open/closed state) needs to show server-fetched content? You cannot import a Server Component into a client file; it would become client code. Instead, pass it in as children (or any JSX prop) from a Server Component parent:
"use client";
import { useState } from "react";
export function Modal({ children }: { children: React.ReactNode }) {
const [open, setOpen] = useState(false);
return (
<>
<button onClick={() => setOpen(true)}>View cart</button>
{open && <div role="dialog">{children}</div>}
</>
);
}import { Modal } from "./_components/Modal";
import { Cart } from "./_components/Cart"; // async Server Component, reads the db
export default function Page() {
return (
<Modal>
<Cart />
</Modal>
);
}Cart renders on the server first; the modal only receives its finished output. Here is the client half running on its own, with plain JSX standing in for the server-rendered cart:
The same trick handles context. React context does not work in Server Components, so you write a small Client Component provider that takes children, and render it in a layout as deep as you can:
"use client";
import { createContext } from "react";
export const ThemeContext = createContext("light");
export default function ThemeProvider({ children }: { children: React.ReactNode }) {
return <ThemeContext.Provider value="dark">{children}</ThemeContext.Provider>;
}Chart.tsx starts with "use client" and imports ReportTable.tsx, which has no directive and calls await db.query(...). What happens?Keeping server code on the server
Because a module can be imported from either side, it is possible to pull server code into the client by accident. Two safety nets:
- Environment variables without the
NEXT_PUBLIC_prefix are never included in client bundles. In the browser they read as empty, so a leaked helper fails rather than exposing the key. - Add
import "server-only"at the top of modules that must never reach the browser (database access, secrets). If a Client Component imports one, the build fails with a clear error.client-onlydoes the reverse for browser-only code.
import "server-only";
export async function getRevenue() {
const res = await fetch("https://api.example.com/revenue", {
headers: { authorization: `Bearer ${process.env.API_KEY}` },
});
return res.json();
}What ships to the browser?
"use client" marks a boundary in the module graph. A module marked client: true, and every module it imports (directly or indirectly), ends up in the client JavaScript bundle. Server modules that are only imported by other server modules stay on the server.
Given a map of modules and the entry (a server page), return the names of the modules that ship to the browser, sorted alphabetically.
entry = "page"
page: { client: false, imports: ["Header", "LikeButton"] }
Header: { client: false, imports: [] }
LikeButton: { client: true, imports: ["Icon"] }
Icon: { client: false, imports: [] }
→ ["Icon", "LikeButton"]Imports can form cycles. Every imported name exists in the map.
- Server Component
- The default in
app/: renders only on the server, can be async, can use secrets, and sends no component JavaScript to the browser. - Client Component
- A component in a
"use client"module graph: prerendered to HTML, then hydrated in the browser so it can use state, effects and events. - "use client"
- A directive at the top of a file that marks the boundary where the client module graph begins.
- RSC payload
- The serialised output of Server Components, with placeholders and props for Client Components, used to build HTML and update the page on navigation.
- hydration
- React attaching event handlers and state to server-rendered HTML so it becomes interactive.
- server-only
- A package you import in server modules so that importing them from client code fails the build.