Sub topic 4
Defining Server Functions inline and in a "use server" file
This chapter shows the two places you can write a Server Function, what each form allows, and how to choose between them. It assumes you know React components and hooks, async/await, and HTML forms with FormData. It also assumes you know the earlier chapters' point that "use server" marks functions callable from the client, and that it does not mark Server Components.
The two forms
A Server Function is an async function that runs on the server. You create one by putting the "use server" directive in one of two places:
- File level. The directive is the first statement in a file. Every export of that file becomes a Server Function.
- Function level. The directive is the first statement inside one async function body. Only that function becomes a Server Function.
Both forms produce the same kind of thing. The bundler replaces the function on the client side with a reference. When client code calls the reference, the framework sends a request to the server. The server runs the real function and sends the result back.
The function body never ships to the browser. Only an identifier for it does.
Form 1: a "use server" file
Put the directive at the top of a module. Place it before any import statement. Comments may come before it, but code may not.
// 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.
Rules for this form:
- Every export must be an async function. Exporting a constant, a plain function, or an object from a
"use server"file causes a build or runtime error. The bundler needs each export to be a callable endpoint. - Every export is reachable by clients. If you export
deleteAllNotesto share it between two server modules, a client can now call it too. Keep shared server helpers in a file without the directive. - Non-exported functions stay private. A helper declared in the file but not exported is ordinary server code. No endpoint exists for it.
- The directive applies to the file, not to its importers. A Server Component can import from this file, and so can a Client Component.
The last rule is what makes this form flexible. A Client Component can import a Server Function and call it, because the import resolves to a reference in the client bundle.
// 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>
);
}This example assumes createNote takes (prevState, formData) as in the useActionState chapter. The call site and the function signature must agree.
Form 2: an inline function in a Server Component
Inside a Server Component you can define the function next to the JSX that uses it. Put "use server" as the first statement of the function body.
// 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>
);
}Rules for this form:
- The function must be async. The directive on a non-async function is an error.
- The directive must be the first statement. Any code before it, including a variable declaration, means the string is just an expression and does nothing.
- It works only in Server Components. A file that starts with
"use client"cannot contain an inline"use server"function. Client Components must import their Server Functions from a"use server"file or receive them as props. - The file itself is not a
"use server"file. The page's default export stays a Server Component. Only the marked function becomes an endpoint.
Passing an inline function to a Client Component
A Server Component can pass a Server Function to a Client Component as a prop. This works because a Server Function is one of the values React can serialize across the boundary, as a reference.
// app/page.js (a Server Component)
import { db } from './db';
import { NoteFormClient } from './NoteFormClient';
export default function Page() {
async function createNote(prevState, formData) {
'use server';
const title = String(formData.get('title') ?? '').trim();
if (title.length === 0) {
return { error: 'Title is required.' };
}
await db.notes.insert({ title });
return { error: null };
}
return <NoteFormClient action={createNote} />;
}// app/NoteFormClient.js
'use client';
import { useActionState } from 'react';
export function NoteFormClient({ action }) {
const [state, formAction, isPending] = useActionState(action, { 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>
);
}The Client Component never imports anything from the server. It receives a reference and calls it.
Closures in inline functions
An inline function can read variables from the Server Component around it. That is a closure. In the example below, userId comes from the enclosing scope.
// app/Profile.js (a Server Component)
import { db } from './db';
export default async function Profile({ userId }) {
async function resetBio() {
'use server';
await db.users.update(userId, { bio: '' });
}
return (
<form action={resetBio}>
<button type="submit">Clear bio</button>
</form>
);
}Mechanically, the captured value has to travel with the reference. The page sends it to the browser, and the browser sends it back when the form is submitted. Three consequences follow:
- Captured values must be serializable. A database connection or a class instance cannot be captured.
- Treat captured values as client-controlled. A caller can try to tamper with them, even when a framework takes steps such as encrypting them. Verify ownership on the server, as the security chapter explains.
- Values are fixed at render time. The function sees the
userIdfrom the render that produced the form, not a newer one.
If you want the arguments to be explicit, use bind, which a later chapter covers. If you want no captured data at all, move the function to a "use server" file and read what you need there, for example from the session.
Choosing between the forms
| Concern | Inline | `"use server"` file |
|---|---|---|
| Where it can be defined | Server Components only | Any module with the directive first |
| Imported by Client Components | No, pass it as a prop | Yes |
| Reuse across files | Awkward | Natural |
| Closure over render data | Yes | No |
| Surface area | One function | Every export |
| Testing in isolation | Harder | Import and call it |
A reasonable default is to use files for anything with real logic, and inline functions for small, single-use handlers. A single actions.js per feature keeps the endpoints easy to audit, because you can see every callable function by reading the exports.
Common errors
- Directive after an import. In a file-level setup,
'use server'below animportis not treated as a directive. The module is then ordinary code, and its functions will not become Server Functions. - Non-async export.
export const LIMIT = 10;in a"use server"file fails. Move constants to a separate module. - Inline function in a Client Component. This fails at build time. Move the function to a
"use server"file and import it. - Exporting a helper by accident. A utility like
export async function getUserOrThrow()in an actions file is now a public endpoint. Keep helpers in a non-directive module. - Confusing the two directives.
"use client"marks a module boundary where Client Components start."use server"marks callable server functions. Neither one is the opposite of the other, and a Server Component needs no directive. - Assuming the inline form is private. An inline function is still reachable by a crafted request. Placement in your source does not change that. Validate input and check permissions in every function, as shown here.
// 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);
}Summary
- File-level
"use server"turns every export of a file into a Server Function. All exports must be async. - Function-level
"use server"turns one async function in a Server Component into a Server Function. - Client Components cannot define Server Functions inline. They import them or receive them as props.
- Inline functions can close over render-time values. Those values are serializable and should be treated as client-controlled.
- Both forms create public endpoints.
Exercise
A teammate adds export const MAX_TITLE_LENGTH = 100; to app/actions.js, which starts with 'use server';. The build fails. Why, and what is the fix? Also, the same file has an exported helper export async function loadAllNotes() that is meant only for server-side use by other modules. What is wrong with that?
Show answer
A "use server" file may export only async functions, because each export becomes a callable endpoint. A constant is not one. Fix it by moving MAX_TITLE_LENGTH into a separate module without the directive, and importing it where needed. The exported loadAllNotes is a problem too. Every export of a "use server" file is a Server Function that a client can call, so it is exposed even though it was meant for internal use. Move it to a module without the directive, or stop exporting it, and keep only the functions that are meant to be callable in the actions file.
Exercise
You need a delete button in a Client Component that is marked 'use client'. You try writing async function remove() { 'use server'; ... } inside that component. Why does this not work, and what are two valid ways to give the component a Server Function?
Show answer
Inline "use server" functions are allowed only in Server Components. A Client Component cannot define one. First option: put the function in a file that begins with 'use server' and import it into the Client Component. Second option: define the function (inline or in a file) in a Server Component and pass it down as a prop.