Skip to content

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.

16 min read0/5 questions

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:

  1. It can be async and await data directly. No useEffect, no loading state juggling.
  2. It can use secrets and server-only libraries (database clients, API keys, the file system) safely.
  3. It adds zero JavaScript to the client bundle. A page that only renders a list ships no code for that list.
app/products/page.tsx
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.

Quick check
You add const [open, setOpen] = useState(false) to a component in app/products/page.tsx with no directive at the top. What happens?
Need a nudge? A hint rules out a wrong answer.

The "use client" boundary

To make a component interactive, put the "use client" directive at the very top of its file, above the imports:

app/products/_components/AddToCart.tsx
"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.

A product page: where each component runs
Pageserver: fetches productLogoserverSearchBar"use client"HeaderserverProductInfoserver: reads dbSpinnerimported by AddToCartAddToCart"use client"Reviewsserver: asyncroot

Everything is a Server Component by default. On its own, this page would ship no component JavaScript.

1/4

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.

Match the pairs0/5 matched

Server Component or Client Component?

Choose an item, then its match on the other side.

How the two kinds of component meet

On a first page load, the work splits like this:

Put it in order5 steps

Put the first page load of a mixed page in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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

app/products/[id]/page.tsx
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.

TypeScriptserializable.ts
function problem(value: unknown, path = "props"): string | null { if (value === null || ["string", "number", "boolean", "undefined"].includes(typeof value)) return null; if (typeof value === "function") return `${path} is a function`; if (value instanceof Date || value instanceof Map || value instanceof Set) return null; if (Array.isArray(value)) { for (const [i, v] of value.entries()) { const p = problem(v, `${path}[${i}]`); if (p) return p; } return null; } if (Object.getPrototypeOf(value) !== Object.prototype) return `${path} is a class instance`; for (const [k, v] of Object.entries(value as object)) { const p = problem(v, `${path}.${k}`); if (p) return p; } return null;} class Money { constructor(public cents: number) {} } console.log(problem({ id: "p1", tags: ["new"], added: new Date() }) ?? "ok");console.log(problem({ id: "p1", onAdd: () => {} }) ?? "ok");console.log(problem({ price: new Money(1299) }) ?? "ok");
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputTypeScript

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(","));
Need a nudge? Hints walk you through it.

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:

app/_components/Modal.tsx
"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>}
    </>
  );
}
app/page.tsx
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:

Reactmodal-slot.tsx
import { useState } from "react"; function Modal({ children }: { children: React.ReactNode }) { const [open, setOpen] = useState(false); return ( <div style={{ fontFamily: "system-ui" }}> <button onClick={() => setOpen(!open)}>{open ? "Close cart" : "View cart"}</button> {open && <div role="dialog" style={{ border: "1px solid #ccc", padding: 12, marginTop: 8 }}>{children}</div>} </div> );} export default function App() { // In Next.js this <ul> would come from <Cart />, rendered on the server. return ( <Modal> <ul> <li>Coffee grinder x1</li> <li>Filters x2</li> </ul> </Modal> );}

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:

app/theme-provider.tsx
"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>;
}
Quick check
Chart.tsx starts with "use client" and imports ReportTable.tsx, which has no directive and calls await db.query(...). What happens?
Need a nudge? A hint rules out a wrong answer.

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-only does the reverse for browser-only code.
lib/data.ts
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();
}
ChallengeMedium

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.

TypeScript
type Mod = { client: boolean; imports: string[] }; function clientBundle(modules: Record<string, Mod>, entry: string): string[] { // Walk the graph; remember whether you are already inside a client boundary. return [];}
Key terms
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.