Server and Client Components
Know which code runs on the server and which in the browser, and draw the boundary so pages are fast and secrets stay safe.
Intermediate · about 6 hours · difficulty 4/5
Learn first: Next.js Routing and Layouts
In the App Router, components are Server Components by default. They run on the server, can read the database directly, and send HTML plus a compact payload to the browser with no component JavaScript.
Client Components
Add "use client" at the top of a file when a component needs interactivity: state, effects, event handlers or browser APIs. Everything it imports becomes part of the client bundle.
Drawing the boundary
- Keep pages and data-loading components on the server.
- Push "use client" down to the smallest interactive leaf: a LikeButton, a FilterBar, a Modal.
- Pass server-fetched data to client components as serialisable props (plain objects, not class instances or functions).
- Server components can render client components, and you can pass server components into client components as children.
Security implications
Server-only code can use secrets and database clients. Mark modules with the server-only package so an accidental client import fails the build. Environment variables are only exposed to the browser if prefixed with NEXT_PUBLIC_.
Pitfalls
- Adding "use client" to a whole page because one button needs state, shipping far more JavaScript than needed.
- Importing a database client into a client component.
- Passing entire database rows (with private fields) as props to the client.
You are ready to move on when you can take a page, mark exactly which components must be client components, and explain what each one sends to the browser.
Key concepts
- Server Components by default
- "use client" and the client boundary
- Composition patterns
- Serialisable props
- server-only and secrets
- NEXT_PUBLIC_ environment variables
- Suspense and streaming
Mini project
Build a company details page that loads data in a server component and includes two small client components (an Apply button with state and a tabbed view), then measure the client JavaScript before and after moving the boundary.
Check yourself
Your page component is a client component because of one interactive search box. How would you restructure it?
Free resources
- Server and Client Components (Next.js)
- Server Components (React)
- 'use client' directive (React)