Sub topic 1
Where Server and Client Components Run
Server Functions only make sense once you know where each piece of React code executes. This chapter builds that model. It covers the two environments, the module boundary between them, and the directives that mark it. Later chapters build on this model to define, call, and secure Server Functions.
Prerequisites
This chapter assumes you have the following:
- Solid knowledge of React components, props, state, and hooks.
- Familiarity with
async/awaitand Promises in JavaScript. - A basic understanding of HTML forms and
FormData. - Awareness of how an HTTP request and response flow between a browser and a server.
You do not need prior experience with a specific framework. Examples use file paths like app/page.js because frameworks that support Server Components commonly use that layout, but the ideas are the same in any setup.
Two environments, one component tree
A React application that uses Server Components runs in two places.
- The server environment is a Node.js process, an edge runtime, or a build step. It can read files, query databases, and use secrets. It never runs in the user's browser.
- The client environment is the browser. It handles clicks, keeps state, and uses browser APIs such as
windowandlocalStorage.
A Server Component is a component that renders only in the server environment. A Client Component is a component that renders on the client. Client Components are also usually pre-rendered to HTML on the server for the first page load, and then hydrated in the browser. Hydration means React attaches event handlers to the existing HTML so it becomes interactive.
The important point is that these are not two separate apps. They are one component tree. A Server Component can render a Client Component, and the result is sent to the browser as one tree.
Server Components run once per request or once per build. They have no state, no effects, and no event handlers, because there is no live browser session to hold them. Their code is not sent to the browser. Only their output is.
What each kind of component can do
| Capability | Server Component | Client Component |
|---|---|---|
| Read a database or file system directly | Yes | No |
| Use secrets and environment variables safely | Yes | No |
| Use `useState`, `useReducer`, `useEffect` | No | Yes |
| Attach `onClick` and other event handlers | No | Yes |
| Use browser APIs such as `window` | No | Yes |
| Be `async` and `await` data in the component body | Yes | No |
| Code shipped to the browser | No | Yes |
The async row is a common surprise. A Server Component can be declared async and can await data directly:
// app/page.js (a Server Component)
import { db } from './db';
export default async function Page() {
const notes = await db.notes.findAll();
return (
<ul>
{notes.map((note) => (
<li key={note.id}>{note.title}</li>
))}
</ul>
);
}Here db is a placeholder for your data layer. A Client Component cannot be async in this way.
The module boundary
React decides where code runs by module, meaning by file. It does not decide per component. Each file is either part of the server module graph or the client module graph.
By default, a file is a Server Component module in a setup that supports Server Components. You mark the switch to the client with the 'use client' directive. A directive is a string literal placed at the top of a file or function body. It tells the bundler how to treat the code. It is not a function call or an import.
// app/Counter.js
'use client';
import { useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}The 'use client' line must be at the very top of the file, before any imports. It marks a boundary. The file and everything it imports become part of the client bundle.
This has two consequences you should remember.
- You do not repeat the directive in every file. A module imported by a
'use client'file is already on the client side. Only the entry point of the client subtree needs the directive. - The boundary is about imports, not about the tree. A Client Component can still render Server Components if they arrive as
childrenor other props, because the server renders them before they cross the boundary.
Passing Server Components through children
A Client Component cannot import a Server Component. Importing would pull the server code into the client bundle. You can, however, pass a Server Component as children:
// app/Panel.js
'use client';
import { useState } from 'react';
export function Panel({ children }) {
const [open, setOpen] = useState(true);
return (
<section>
<button onClick={() => setOpen(!open)}>Toggle</button>
{open && children}
</section>
);
}// app/page.js (a Server Component)
import { Panel } from './Panel';
import { Notes } from './Notes';
export default function Page() {
return (
<Panel>
<Notes />
</Panel>
);
}Notes is a Server Component. The server renders it, and Panel receives the finished output as children. Panel does not know or care that it came from the server.
What crosses the boundary
When a Server Component renders a Client Component, the props it passes are sent over the network. That means the props must be serializable, which means they can be turned into a form that travels in a response. Strings, numbers, booleans, plain objects, arrays, Date values, Map, Set, and Promises can cross. Ordinary functions, class instances, and symbols that are not registered cannot.
// app/page.js (a Server Component)
import { Counter } from './Counter';
export default function Page() {
// Fine: a number and a string are serializable.
return <Counter start={5} label="Clicks" />;
}This would fail:
// app/page.js (a Server Component)
import { Counter } from './Counter';
export default function Page() {
function format(n) {
return `#${n}`;
}
// Error: a plain function cannot be sent to a Client Component.
return <Counter format={format} />;
}The function format lives on the server and cannot be sent to the browser as code. There is one exception to this rule, and it is the subject of the rest of this tutorial: a function marked as a Server Function can cross the boundary, because React sends a reference to it instead of the code.
Where `'use server'` fits
The two directives are not opposites in the way their names suggest. They mark different things.
| Directive | What it marks | Direction |
|---|---|---|
| `'use client'` | A file as the entry to client code | Server code importing client code |
| `'use server'` | A function as callable from the client | Client code calling server code |
A common mistake is to think 'use server' marks a Server Component. It does not. Server Components are the default and need no directive. 'use server' marks Server Functions, which are async functions that run on the server and that client code can call. The next chapter covers exactly what the directive marks and what it does not.
Common errors at the boundary
- Using a hook in a Server Component. Calling
useStateoruseEffectin a file without'use client'raises an error. Fix it by moving the interactive part into a small Client Component. - Adding
'use client'too high in the tree. Marking a large layout as a Client Component pulls everything it imports into the browser bundle. Keep Client Components small and near the leaves. - Passing a function as a prop across the boundary. This fails serialization, as shown above. Pass data, or pass a Server Function.
- Importing server-only code into a Client Component. A database client or a secret imported from a client file ends up in the bundle. If you want a guarantee, many setups support a
server-onlypackage that throws a build error when a client file imports it. - Putting the directive after an import. A directive that is not at the top of the file is treated as an ordinary string and is ignored.
How this connects to Server Functions
The boundary model gives you three facts to carry forward.
- Server code never reaches the browser. Only its output does.
- Client code runs on the user's machine, so users can inspect and change it.
- Anything that crosses from client to server is a network request, even when it looks like a function call.
The third fact matters most. When a Client Component calls a Server Function, the browser sends an HTTP request and the server runs the function. Because users control what the browser sends, a Server Function must treat its arguments as untrusted input. The security chapter develops this point.
Exercise
A file app/Menu.js starts with 'use client' and imports ./helpers.js, which does not have a directive. Does helpers.js run on the server or in the browser? Can a Server Component then import Menu and pass it an inline function as a prop?
Show answer
helpers.js is part of the client module graph, because it is imported by a 'use client' file, so it runs in the browser (and in the pre-render on the server). A Server Component can import Menu, but it cannot pass an ordinary inline function as a prop. Functions are not serializable across the boundary. It could pass serializable data, or a Server Function, which React sends as a reference.
Exercise
You need a page that loads notes from a database and also has a toggle button that shows or hides the list. Which parts should be Server Components and which should be Client Components? Describe the structure.
Show answer
Make the page a Server Component that awaits the database query and renders the notes. Put the toggle in a small Client Component, such as Panel, that holds the open/closed state with useState and renders children. The page passes the rendered notes list to Panel as children. The database code stays on the server, and only the small toggle component ships to the browser.