Server and Client Components
This is the core concept of the modern Next.js App Router. Every component runs in one of two environments, and choosing well makes your app faster, simpler and more secure.
Two kinds of components
| Server Component (default) | Client Component ('use client') |
|
|---|---|---|
| Runs | On the server (at build time or per request) | On the server for the first HTML, then in the browser |
| JavaScript sent to the browser | None | Yes |
async/await, database queries, file system, secrets |
✓ | ✗ |
useState, useEffect, event handlers (onClick) |
✗ | ✓ |
Browser APIs (window, localStorage) |
✗ | ✓ |
Server Components: fetch data where it lives
// app/products/page.tsx — a Server Component
import { db } from '@/lib/db';
export default async function ProductsPage() {
const products = await db.product.findMany({ orderBy: { createdAt: 'desc' } });
// This code — and the DB credentials it uses — never reaches the browser.
return (
<ul>
{products.map((p) => (
<li key={p.id}>{p.name} — ${p.price}</li>
))}
</ul>
);
}Benefits: no loading spinners for the initial data, no API layer needed to read data, smaller JS bundles, and secrets stay on the server.
Client Components: add interactivity
Add 'use client' at the top of the file to mark it (and everything it imports) as client code:
// app/products/add-to-cart.tsx
'use client';
import { useState } from 'react';
export function AddToCartButton({ productId }: { productId: string }) {
const [added, setAdded] = useState(false);
return (
<button onClick={() => setAdded(true)} disabled={added}>
{added ? '✓ Added' : 'Add to cart'}
</button>
);
}Try that component live:
Composing them: the boundary
Server Components can render Client Components and pass them serialisable props (strings, numbers, plain objects and arrays, Dates, Promises):
// app/products/page.tsx (Server)
import { AddToCartButton } from './add-to-cart';
export default async function Page() {
const products = await getProducts();
return products.map((p) => (
<div key={p.id}>
<h2>{p.name}</h2> {/* static: rendered on the server, zero JS */}
<AddToCartButton productId={p.id} /> {/* interactive island */}
</div>
));
}Server tree: Page ─┬─ <h2> (server)
└─ AddToCartButton ← 'use client' boundary: this part ships JSRules of the boundary:
- You can't pass functions from a Server Component to a Client Component as props (except Server Actions).
- A Client Component can't import a Server Component, but it can receive one as
children:
// ✓ The "children" pattern: a client wrapper around server content
'use client';
export function Collapsible({ children }: { children: React.ReactNode }) {
const [open, setOpen] = useState(true);
return <div><button onClick={() => setOpen(!open)}>Toggle</button>{open && children}</div>;
}
// In a Server Component:
<Collapsible>
<ServerRenderedReviews /> {/* still rendered on the server */}
</Collapsible>Push 'use client' down the tree
A common beginner mistake is marking the whole page 'use client' because one button needs onClick. That ships the entire page as JavaScript and loses server data fetching.
✗ page.tsx ('use client') → everything is client-side
✓ page.tsx (server)
├── ProductDetails (server)
├── Reviews (server)
└── <AddToCartButton/> ('use client') ← only the interactive leafKeep server-only code on the server
Mark modules that must never reach the browser:
// lib/db.ts
import 'server-only'; // build error if a Client Component imports this
export const db = createDbClient(process.env.DATABASE_URL!);Environment variables: only variables prefixed NEXT_PUBLIC_ are bundled into browser code. Everything else (DATABASE_URL, STRIPE_SECRET_KEY) is available only on the server.
Context providers
Context needs a Client Component, so wrap providers in a client file and use it in a layout:
// app/providers.tsx
'use client';
import { ThemeProvider } from './theme';
export function Providers({ children }: { children: React.ReactNode }) {
return <ThemeProvider>{children}</ThemeProvider>;
}
// app/layout.tsx (Server)
import { Providers } from './providers';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return <html lang="en"><body><Providers>{children}</Providers></body></html>;
}Decision guide
Use a Server Component when you fetch data, use secrets, render mostly static content, or use large libraries (like markdown parsers) that you don't want to ship.
Use a Client Component when you need useState/useEffect, event handlers, browser APIs, or client-only libraries (charts, maps, animations).
Practice (in your project)
- Create a Server Component page that fetches
https://jsonplaceholder.typicode.com/posts?_limit=5and lists the titles. - Add a Client Component
LikeButtonnext to each title with its own like counter. - Wrap the list in a client
Collapsiblethat receives the server-rendered list aschildren.
1.A component uses useState. What must its file start with?
2.Why avoid marking an entire page 'use client'?