Lesson 7 / 25

Server Components

Async components that run on the server.

Fetch data where it lives

Server Components (the default in app/) run only on the server. They can be async, query databases or APIs directly, read secrets safely, and their code is not sent to the browser, keeping bundles small. They cannot use state, effects or browser APIs, and cannot attach event handlers. Use them for data loading and non-interactive UI, and pass data down to Client Components where interaction is needed.

Where code runs

Server Components fetch data and render HTML; Client Components add interactivity.

Three ideas: Server Components, Client Components, the boundary.
Figure 3.1 — Server, client and the boundary.

An async Server Component page

This file is from a small demo store I built with Next.js 16.3.8, React 19.3 and TypeScript; next build compiled and type-checked it successfully. The home page awaits product data directly; no API call from the browser and no loading spinner needed.

import Link from "next/link";
import { getProducts } from "@/lib/data";

export default async function HomePage() {
  const products = await getProducts();        // runs on the server
  return (
    <ul>
      {products.map((p) => (
        <li key={p.id}>
          <Link href={`/products/${p.id}`}>{p.name}</Link> - Rs {p.price}
        </li>
      ))}
    </ul>
  );
}

The HTML the server sends, run

I built the demo store with next build (Next.js 16.3.8), started it with next start and requested pages with curl; the output is copied from that run, trimmed to the relevant lines. The list is in the initial HTML, which is good for performance and search engines.

curl -s http://localhost:3917/

Output:

<title>Stationery Shop</title>
<ul><li><a href="/products/1">Notebook</a> - Rs 120</li><li><a href="/products/2">Fountain pen</a> - Rs 899</li><li><a href="/products/3">Desk lamp</a> - Rs 1499</li></ul>

Quick check: Which is allowed in a Server Component?

  • Awaiting a database query directly
  • useState
  • onClick handlers
  • Reading window.localStorage
Answer

Awaiting a database query directly — Server Components run on the server only.