Sub topic 2
What "use server" marks (and what it does not)
This chapter assumes you know React components, props and hooks. It also assumes you can read async/await code and know that a Server Component renders on the server and a Client Component renders in the browser. The previous chapter covered where each kind of component runs. This chapter covers the "use server" directive and the mistakes people make because of its name.
The short version
"use server" marks functions that run on the server and that client code is allowed to call. It does not mark a component as a Server Component. It does not mark code as "server-only". It is the counterpart of "use client" only in the sense that both sit on the server/client boundary. They mark different things.
| Directive | What it marks | Direction of the boundary |
|---|---|---|
| `"use client"` | A module, and everything it imports, as client code | Server code imports client code, which is sent to the browser |
| `"use server"` | An async function, or every export of a module, as callable from the client | Client code calls server code over the network |
Server Components need no directive. In a framework with React Server Components, components are Server Components by default, and you opt into client code with "use client".
The two forms of the directive
A directive is a string literal written as a statement, like 'use strict'. React supports it in two positions.
File level
Put the directive at the very top of a file, before any imports. Every export of the file becomes a Server Function.
// app/actions.js
'use server';
import { db } from './db';
export async function createNote(formData) {
const title = formData.get('title');
await db.notes.insert({ title });
}Here db is a placeholder for your data layer. The file never ships to the browser as code. The client bundle receives a reference to createNote, which is enough to call it.
Function level
Put the directive as the first statement inside an async function body. That one function becomes a Server Function. This form works only inside a Server Component, because the file as a whole must be server code.
// app/page.js (a Server Component)
import { db } from './db';
export default function Page() {
async function createNote(formData) {
'use server';
await db.notes.insert({ title: formData.get('title') });
}
return (
<form action={createNote}>
<input name="title" required />
<button type="submit">Add note</button>
</form>
);
}The function is passed to the form's action prop. When the user submits, the browser does not run the function. It sends a request to the server, and the server runs it.
How the two directives relate
Think of the module graph as two worlds. Server code can import client modules, and "use client" marks where that crossing happens. Client code cannot import server modules. The only way for it to reach server code is through a Server Function, and "use server" marks where that crossing happens.
The two arrows go in opposite directions. The first one is an import resolved at build time. The second one is a network request made at run time.
What "use server" does not mean
It does not make a Server Component
A common mistake is to write 'use server' at the top of a page file because "this page runs on the server". In a Server Components framework, the page already does. Adding the directive changes the meaning: every export in that file now becomes a callable endpoint, and a default-exported component is not an async function returning data, so it is the wrong kind of export. Leave the directive off components.
It does not hide code from the client by itself
The directive keeps the function body out of the browser bundle. That is a benefit, but it is not a secrecy guarantee for everything near it. If you put a secret in a value that you return from a Server Function, or pass a secret as a prop to a Client Component, the secret reaches the browser. The directive protects the function's source, not the data that flows out of it.
It does not make a function private
This is the most important point. Marking a function with "use server" creates a network entry point. Anyone who can reach your app can send a request to it, with any arguments, whether or not your UI shows a button for it. A later chapter on security covers this in depth. For now, keep this rule: a Server Function is a public endpoint, so treat its arguments as untrusted input.
// app/actions.js
'use server';
import { getSession } from './auth';
import { db } from './db';
export async function deleteNote(noteId) {
if (typeof noteId !== 'string') {
throw new Error('Invalid note id');
}
const session = await getSession();
if (!session) {
throw new Error('Not signed in');
}
const note = await db.notes.find(noteId);
if (!note || note.ownerId !== session.userId) {
throw new Error('Not allowed');
}
await db.notes.delete(noteId);
}The function checks its own input, the caller's identity, and the caller's permission. It does not rely on the page that renders the delete button to have done so. Here getSession and db are placeholders for your own modules.
It does not mean "any server-side helper"
If you write a helper that only other server code calls, such as a function that formats a database row, do not put it in a "use server" file. Doing so turns it into a public endpoint for no reason. Keep ordinary server helpers in regular modules. Put in a "use server" file only the functions that the client should be able to call.
Rules for the directive
The directive is easy to get subtly wrong. Check these points when a function is not behaving as a Server Function.
- Position. At file level it must come before any
importstatement. Comments before it are fine. Placed after an import, it is just an unused string expression, and nothing is marked. - Quotes. Use single or double quotes. A template literal (backticks) is not recognized as a directive.
- Async only. A Server Function must be
async, because the call crosses the network and always returns a Promise. In a file-level"use server"module, every export must be an async function. Exporting a constant, a class, or a synchronous function from that file is an error in most bundlers. - Function-level placement. The directive must be the first statement in the function body, as
'use server'above, before any other code. - Not in Client Component files. You cannot write an inline
'use server'function inside a file that has'use client'. Define it in a separate"use server"file and import it, as the next example shows.
Using a Server Function from a Client Component
A Client Component imports the function from the "use server" file. After the build step, the import is not the real function. It is a stub that sends a request.
// app/NoteForm.js
'use client';
import { useActionState } from 'react';
import { createNote } from './actions';
export function NoteForm() {
const [state, formAction, isPending] = useActionState(createNote, { error: null });
return (
<form action={formAction}>
<input name="title" />
<button type="submit" disabled={isPending}>Add note</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}useActionState changes how createNote is called. It passes the previous state as the first argument and the FormData as the second, so the function must accept that shape:
// app/actions.js
'use server';
import { db } from './db';
export async function createNote(prevState, formData) {
const title = String(formData.get('title') ?? '').trim();
if (title.length === 0) {
return { error: 'Title is required.' };
}
await db.notes.insert({ title });
return { error: null };
}Later chapters explain useActionState fully. The point here is that the Client Component imports from the "use server" file, and the directive on that file is what makes the import legal.
Common errors and what they mean
| Symptom | Likely cause | Fix |
|---|---|---|
| Build error about a non-async export | A `"use server"` file exports a constant, type helper, or sync function | Move it to a normal module, or make the function async |
| The function runs in the browser or throws "not defined on the client" | The directive is after an import, or is in a template literal | Move it to the top of the file and use plain quotes |
| Error on an inline `'use server'` in a Client Component | Inline directives need server code | Move the function to a `"use server"` file and import it |
| A helper is callable from the browser unexpectedly | It lives in a `"use server"` file | Move it to a regular module |
| A page file with `'use server'` fails or exposes odd endpoints | The directive was used to mean "runs on server" | Remove it from the component file |
Summary of the mental model
"use client"marks code that is sent to the browser."use server"marks functions that the browser can call.- Server Components are the default and need no directive.
- File-level
"use server"exposes every export. Function-level exposes one function, and only inside Server Components. - Every marked function is a public endpoint. Validate input and check authentication and ownership inside it.
Exercise
A teammate puts 'use server' at the top of app/page.js, which default-exports a Server Component, "to make sure it runs on the server". What is wrong with this, and what should they do?
Show answer
Server Components are the default in a Server Components framework, so the page already runs on the server. The directive does not mark components. It marks every export of the file as a Server Function, which turns the file's exports into public endpoints and conflicts with exporting a component. They should remove the directive and, if they need a callable function, define it inline with a function-level 'use server' or in a separate "use server" file.
Exercise
You have a file with 'use server' at the top that exports createNote (async) and also a helper formatTitle (sync) used only by other server code. What should you change, and why?
Show answer
Move formatTitle into a regular module. Every export of a "use server" file must be an async function and becomes a public endpoint. A sync helper breaks the async-only rule, and even if it were async, it would be reachable by clients for no reason.