React Server Components 16 🧬 Server Functions — The “use server” directive for mutations
The "use server" directive is the boundary marker that turns an ordinary async function into a callable endpoint from the client. It is the mechanism behind Server Functions, and when that function is passed to a form action or invoked inside a transition, it becomes a Server Action. The distinction matters less than the contract: the function runs on the server, the client holds only a reference, and every argument that crosses the network must be serializable and treated as untrusted input.
Before September 2024, the React documentation called all of these “Server Actions.” The terminology was updated to reflect that Server Functions can be used for more than mutations—they can be called from event handlers, passed as props, or invoked from useEffect . But the mutation use case is the one that matters most in practice, and it is the one that carries the sharpest security requirements. A Server Function reachable via a direct POST request is a public endpoint whether you intended it to be or not.
Key point: "use server" does not make a function safe. It makes a function callable. Authentication, authorization, and input validation must be written inside the function body, because the client controls every argument and can invoke the function without going through your UI .
Why "use server" exists
The client-to-server function call problem. In a traditional React application, calling a server function from the client required constructing a fetch request, serializing the payload, handling the response, and managing loading states manually. The "use server" directive collapses that into a function call. The bundler replaces the function with a reference, React sends a POST request when the reference is invoked, and the return value is serialized back to the client . The mental model is “call a function,” even though the mechanism is an HTTP request.
The progressive enhancement requirement. A form with a Server Action passed to its action prop works before JavaScript loads. The browser submits the form natively, the server executes the function, and React replays the submission during hydration . This is not a side effect of the directive; it is a design goal. Server Functions passed to forms are meant to work without a client-side runtime, which is why they must be async and why they receive FormData as their first argument in that context.
The serialization constraint. Because arguments and return values cross a network boundary, they must be serializable. Functions, class instances, React elements, and non-global symbols are rejected . This constraint is not arbitrary—it enforces a clean separation between what lives on the server and what the client can hold. A Server Function cannot return a database connection or a class instance, and it cannot accept a callback as an argument. The boundary is strict, and the strictness is the point.
The trade-off. Every Server Function call is a network round-trip. Next.js processes them sequentially on the client, one at a time, which means a slow action blocks subsequent actions . This is by design for mutations, but it makes Server Functions a poor fit for data fetching, which is why React explicitly recommends against using them for that purpose . The directive solves the mutation problem; it does not solve the fetching problem.
a. Defining Server Functions: file-level vs inline
The directive can be placed at the top of a file to mark all exports as Server Functions, or inline at the top of an async function body. The file-level approach is the one that scales.
// app/actions.ts
'use server';
import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
// Every export in this file is a Server Function.
// The bundler creates references for them, and Client Components
// can import and call them directly.
export async function createPost(formData: FormData) {
// The session must be verified inside the function.
// The client controls the arguments; it does not control the session.
const session = await auth();
if (!session?.user) {
throw new Error('Unauthorized');
}
// FormData methods extract the submitted values.
const title = formData.get('title') as string;
const content = formData.get('content') as string;
// Mutate the database only after authorization passes.
await db.post.create({
data: { title, content, authorId: session.user.id },
});
}
The inline form is useful when the function needs to close over values from the Server Component that renders it—a post ID, a user ID, or any other server-side context that the client should not be able to tamper with.
// app/posts/[id]/page.tsx
import { revalidatePath } from 'next/cache';
import { db } from '@/lib/db';
export default async function PostPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
// Inline Server Function: the id is captured from the closure.
// The client never sees the id as a separate argument; it is bound
// into the function reference. This is a security feature, not just convenience.
async function updatePost(formData: FormData) {
'use server';
const title = formData.get('title') as string;
await db.post.update({ where: { id }, data: { title } });
revalidatePath(`/posts/${id}`);
}
return <EditPost updatePostAction={updatePost} />;
}
The closure capture is not merely ergonomic. When a Server Function closes over a value like id, that value is embedded in the function reference token. The client cannot modify it without invalidating the token, which causes the call to be rejected . This makes inline functions with captured context safer than functions that accept the ID as an argument, because an argument is always editable by the client.
b. Invoking Server Functions: forms and event handlers
Server Functions can be invoked from a form’s action prop, from a button’s formAction prop, or from an event handler in a Client Component. The form path gets progressive enhancement; the event handler path requires JavaScript.
// A form with a Server Action
import { createPost } from '@/app/actions';
export function PostForm() {
return (
<form action={createPost}>
<input type="text" name="title" required />
<textarea name="content" required />
<button type="submit">Create Post</button>
</form>
);
}
When the form submits, React passes the form’s FormData to createPost as the first argument. On success, React resets the form’s uncontrolled fields automatically . This is the simplest mutation path, and it works without JavaScript because the browser falls back to a native form submission.
// A Client Component invoking a Server Function from an event handler
'use client';
import { useState } from 'react';
import { incrementLike } from '@/app/actions';
export function LikeButton({ initialLikes }: { initialLikes: number }) {
const [likes, setLikes] = useState(initialLikes);
return (
<button
onClick={async () => {
// The function call triggers a network request.
// The returned value is serialized back to the client.
const updatedLikes = await incrementLike();
setLikes(updatedLikes);
}}
>
Like ({likes})
</button>
);
}
The event handler path does not get progressive enhancement. It requires the client bundle, and it requires the function to be imported from a file with the "use server" directive at the top. The client cannot define a Server Function; it can only import one or receive one as a prop .
c. Security: every argument is untrusted
The Next.js documentation is explicit: Server Functions are reachable via direct POST requests, not just through your application’s UI . A malicious client can invoke createPost with any payload, bypassing any client-side validation you might have written. The function body is the only place where security can be enforced.
// app/actions.ts
'use server';
import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
export async function deletePost(postId: string) {
// 1. Authenticate: who is calling?
const session = await auth();
if (!session?.user) {
throw new Error('Unauthorized');
}
// 2. Authorize: does this user own this post?
const post = await db.post.findUnique({ where: { id: postId } });
if (!post || post.authorId !== session.user.id) {
throw new Error('Forbidden');
}
// 3. Mutate only after both checks pass.
await db.post.delete({ where: { id: postId } });
}
The authorization check cannot be skipped by trusting a client-side guard. If the UI hides a delete button for posts the user does not own, that is a user experience decision, not a security control. The Server Function must repeat the check, because the function can be called from a console, a script, or any HTTP client .
The return value is also a security surface. Returning a raw database record sends every column to the client, including fields the UI does not need. The recommended pattern is to select only what the UI requires and to treat the return value as a public payload .
Complete Example Session
// ============================================
// PART 1: THE ACTIONS FILE
// ============================================
// app/lib/actions.ts
'use server';
import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
// ============================================
// PART 2: A CREATE ACTION WITH AUTHENTICATION
// ============================================
export async function createPost(formData: FormData) {
// Authenticate before touching the database.
const session = await auth();
if (!session?.user) {
throw new Error('Unauthorized');
}
const title = formData.get('title') as string;
const content = formData.get('content') as string;
// Validate the input on the server.
if (!title || title.length < 3) {
return { error: 'Title must be at least 3 characters' };
}
const post = await db.post.create({
data: { title, content, authorId: session.user.id },
});
// Revalidate the list page so the new post appears.
revalidatePath('/posts');
// Redirect after a successful mutation.
// redirect() throws a control-flow exception; code after it does not run.
redirect(`/posts/${post.id}`);
}
// ============================================
// PART 3: A DELETE ACTION WITH OWNERSHIP CHECK
// ============================================
export async function deletePost(postId: string) {
const session = await auth();
if (!session?.user) {
throw new Error('Unauthorized');
}
// Fetch the post to check ownership.
const post = await db.post.findUnique({ where: { id: postId } });
if (!post) {
throw new Error('Post not found');
}
if (post.authorId !== session.user.id) {
throw new Error('Forbidden');
}
await db.post.delete({ where: { id: postId } });
revalidatePath('/posts');
}
// ============================================
// PART 4: A FORM WITH PROGRESSIVE ENHANCEMENT
// ============================================
// app/posts/new/page.tsx
import { createPost } from '@/app/lib/actions';
export default function NewPostPage() {
return (
// The form submits natively before JavaScript loads.
// After hydration, React intercepts and sends it as a Server Function call.
<form action={createPost}>
<input type="text" name="title" required />
<textarea name="content" required />
<button type="submit">Create Post</button>
</form>
);
}
// ============================================
// PART 5: A CLIENT COMPONENT WITH PENDING STATE
// ============================================
// app/posts/new/post-form.tsx
'use client';
import { useActionState } from 'react';
import { createPost } from '@/app/lib/actions';
export function PostForm() {
// useActionState returns the last returned value, the action wrapper,
// and a pending boolean.
const [state, formAction, pending] = useActionState(createPost, null);
return (
<form action={formAction}>
<input type="text" name="title" required disabled={pending} />
<textarea name="content" required disabled={pending} />
{state?.error && <p className="error">{state.error}</p>}
<button type="submit" disabled={pending}>
{pending ? 'Creating…' : 'Create Post'}
</button>
</form>
);
}
// ============================================
// PART 6: CALLING A SERVER FUNCTION FROM AN EVENT HANDLER
// ============================================
// app/posts/[id]/like-button.tsx
'use client';
import { useState, useTransition } from 'react';
import { incrementLike } from '@/app/lib/actions';
export function LikeButton({ postId, initialLikes }: { postId: string; initialLikes: number }) {
const [likes, setLikes] = useState(initialLikes);
const [isPending, startTransition] = useTransition();
const handleClick = () => {
startTransition(async () => {
const updated = await incrementLike(postId);
setLikes(updated);
});
};
return (
<button onClick={handleClick} disabled={isPending}>
{isPending ? '…' : `Like (${likes})`}
</button>
);
}
// ============================================
// PART 7: THE incrementLike ACTION
// ============================================
export async function incrementLike(postId: string) {
const session = await auth();
if (!session?.user) {
throw new Error('Unauthorized');
}
const post = await db.post.update({
where: { id: postId },
data: { likes: { increment: 1 } },
select: { likes: true }, // Return only what the UI needs
});
return post.likes;
}
// ============================================
// PART 8: INLINE SERVER FUNCTION WITH CAPTURED CONTEXT
// ============================================
// app/posts/[id]/page.tsx
import { db } from '@/lib/db';
import { revalidatePath } from 'next/cache';
export default async function PostPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const post = await db.post.findUnique({ where: { id } });
async function updatePost(formData: FormData) {
'use server';
// The id is captured in the closure. The client cannot change it.
const title = formData.get('title') as string;
await db.post.update({ where: { id }, data: { title } });
revalidatePath(`/posts/${id}`);
}
return <EditPost updatePostAction={updatePost} post={post} />;
}
// ============================================
// PART 9: PASSING A SERVER FUNCTION AS A PROP
// ============================================
// app/posts/[id]/edit-post.tsx
'use client';
export function EditPost({
updatePostAction,
post,
}: {
updatePostAction: (formData: FormData) => void;
post: { title: string };
}) {
// The Client Component receives the function reference as a prop.
// It cannot inspect or modify the closure.
return (
<form action={updatePostAction}>
<input type="text" name="title" defaultValue={post.title} />
<button type="submit">Save</button>
</form>
);
}
// ============================================
// PART 10: WHAT NOT TO DO
// ============================================
// ❌ Accepting a userId from the client
export async function badUpdate(formData: FormData) {
const userId = formData.get('userId') as string; // Client-controlled
await db.user.update({ where: { id: userId }, data: { name: 'Hacked' } });
}
// ❌ Trusting that the UI hid the button
export async function badDelete(postId: string) {
// No auth check. The UI hid the button, but the function is still public.
await db.post.delete({ where: { id: postId } });
}
// ❌ Returning raw database records
export async function badFetch() {
return db.user.findMany(); // Includes password hashes, emails, etc.
}
The ten parts covered the definition patterns, the two invocation paths, the security requirements, and the anti-patterns. The through-line is that the directive is thin—it marks a function—and the security is thick—it lives entirely in the function body.
Quick Reference
Directive placement
| Placement | Effect | Use case |
|---|---|---|
| Top of file | All exports are Server Functions | Shared actions file imported by Client Components |
| Top of function body | Only that function is a Server Function | Inline actions that capture server context |
Invocation paths
| Path | Progressive enhancement | Requires JS | Receives |
|---|---|---|---|
<form action={fn}> | Yes | No (before hydration) | FormData |
<button formAction={fn}> | Yes | No (before hydration) | FormData |
| Event handler in Client Component | No | Yes | Arguments you pass |
Serializable types (arguments and returns)
| Supported | Not supported |
|---|---|
| Strings, numbers, booleans, null, undefined | Functions (except Server Functions) |
| BigInt | Class instances |
| Arrays, objects with plain prototypes | React elements / JSX |
| Globally registered Symbols | Non-global Symbols |
Date, Map, Set, FormData | Events |
Security checklist
| Check | Where | Why |
|---|---|---|
| Authenticate the session | Inside the function | The function is a public endpoint |
| Authorize the operation | Inside the function | The UI guard is not a security control |
| Validate input | Inside the function | Client arguments are untrusted |
| Return only needed fields | The return statement | Return values are serialized to the client |
Best Practices
✅ Do This:
// Authenticate inside every Server Function
const session = await auth(); if (!session) throw new Error('Unauthorized'); // ✅
// Capture context in a closure instead of accepting it as an argument
async function update() { 'use server'; await db.update({ where: { id } }); } // ✅
// Return only the fields the UI needs
return { id: user.id, name: user.name }; // ✅
// Use useActionState for pending and error states in forms
const [state, action, pending] = useActionState(createPost, null); // ✅
// Revalidate cache after mutations
revalidatePath('/posts'); // ✅
❌ Don’t Do This:
// Accept a userId from the client
const userId = formData.get('userId'); // ❌
// Skip authorization because the UI hides the button
await db.post.delete({ where: { id: postId } }); // ❌
// Return raw database records
return db.user.findMany(); // ❌
// Use Server Functions for data fetching
// They are designed for mutations; use Server Components for reads. // ❌
// Define a Server Function in a Client Component
'use client'; async function action() { 'use server'; } // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Unauthorized mutation succeeds | No auth check inside the function | Add const session = await auth() at the top |
| User can edit another user’s data | Ownership not checked | Fetch the record and compare authorId to session.user.id |
| Serialization error on return | Returning a class instance or function | Return plain objects with only serializable fields |
| Form submits but nothing happens | Function not async | "use server" requires an async function |
| Client Component import fails | Directive not at file level | Add 'use server' to the top of the module, not inside a function |
| Closure value tampered | Accepting ID as argument instead of capturing it | Move the ID into the closure or bind it |
Real-World Examples
1. Create with authentication
export async function create(formData: FormData) {
'use server';
const session = await auth();
if (!session) throw new Error('Unauthorized');
await db.create({ data: { userId: session.user.id } });
}
2. Delete with ownership check
const post = await db.post.findUnique({ where: { id } });
if (post.authorId !== session.user.id) throw new Error('Forbidden');
await db.post.delete({ where: { id } });
3. Form with useActionState
const [state, action, pending] = useActionState(createPost, null);
return <form action={action}><button disabled={pending}>Save</button></form>;
4. Event handler with transition
startTransition(async () => { const result = await increment(); setLikes(result); });
5. Inline closure capture
async function update() { 'use server'; await db.update({ where: { id } }); }
6. Return only needed fields
return db.user.findUnique({ where: { id }, select: { name: true } });
7. Redirect after mutation
revalidatePath('/posts');
redirect(`/posts/${post.id}`);
8. Pass action as prop
<ClientComponent updateItemAction={updateItem} />
9. Sequential dispatch awareness
// Server Functions run one at a time on the client.
// Do not use them for parallel data fetching. // Awareness
10. Proxy does not transform directives
// A Server Function imported into proxy.ts runs as a normal function.
// Do not rely on "use server" behavior inside proxy. // Caveat
Visual
The Directive Boundary
┌──────────────────────────────────────────────────────────────┐
│ WHERE "use server" LIVES AND WHAT IT DOES │
│ │
│ Server File (app/actions.ts) │
│ ┌──────────────────────────────────────────────┐ │
│ │ 'use server'; │ │
│ │ │ │
│ │ export async function createPost(formData) { │ │
│ │ // Runs on the server. │ │
│ │ // Receives serialized arguments. │ │
│ │ // Returns serialized values. │ │
│ │ } │ │
│ └──────────────────────────────────────────────┘ │
│ │ │
│ │ Bundler creates a reference │
│ ▼ │
│ Client Component (app/form.tsx) │
│ ┌──────────────────────────────────────────────┐ │
│ │ 'use client'; │ │
│ │ import { createPost } from './actions'; │ │
│ │ │ │
│ │ <form action={createPost}> │ │
│ │ {/* The client holds a reference, not │ │
│ │ the function body. */} │ │
│ └──────────────────────────────────────────────┘ │
│ │
│ The directive is the boundary. Everything inside the │
│ function body is server-only. The reference is all the │
│ client ever sees. │
└──────────────────────────────────────────────────────────────┘
Two Invocation Paths
┌──────────────────────────────────────────────────────────────┐
│ FORM ACTION vs EVENT HANDLER │
│ │
│ Form Action Event Handler │
│ ┌────────────────────┐ ┌────────────────────┐ │
│ │ <form action={fn}> │ │ onClick={async () =>│ │
│ │ │ │ await fn() │ │
│ │ Works without JS │ │ Requires JS │ │
│ │ Receives FormData │ │ Receives arguments │ │
│ │ Auto-resets form │ │ Manual state mgmt │ │
│ │ Progressive │ │ No progressive │ │
│ └────────────────────┘ └────────────────────┘ │
│ │
│ Choose form when the mutation is a submission. │
│ Choose event when the mutation is an interaction. │
└──────────────────────────────────────────────────────────────┘
The Security Surface
┌──────────────────────────────────────────────────────────────┐
│ WHAT THE CLIENT CONTROLS │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ Client sends: │ │
│ │ - Any arguments (serialized) │ │
│ │ - Any invocation timing │ │
│ │ - Any request frequency │ │
│ │ - Bypasses all UI guards │ │
│ └──────────────────────┬───────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────┐ │
│ │ Server Function body must: │ │
│ │ 1. Authenticate (who is calling?) │ │
│ │ 2. Authorize (can they do this?) │ │
│ │ 3. Validate (is the input sane?) │ │
│ │ 4. Constrain return (what leaks?) │ │
│ └──────────────────────────────────────────────┘ │
│ │
│ The UI guard is a courtesy. The function body is the │
│ security boundary. │
└──────────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Directive | "use server" (single or double quotes, not backticks) |
| Placement | Top of file or top of async function body |
| Requirement | Must be an async function |
| Invocation | <form action>, <button formAction>, or event handler |
| Form argument | FormData automatically passed |
| Progressive enhancement | Available for form actions, not event handlers |
| Security | Arguments are untrusted; authenticate and authorize inside |
| Serialization | Plain objects, primitives, Date, Map, Set; not functions or classes |
| Return values | Only what the UI needs; raw records leak data |
Key takeaways:
- The directive marks a boundary, not a safety guarantee. A Server Function is a public endpoint. Every call must authenticate the session and authorize the operation inside the function body, because the client can invoke the function without going through your UI .
- Closure capture is safer than argument passing. When a Server Function closes over a value like a post ID, that value is bound into the function reference and cannot be tampered with. An ID passed as an argument is client-controlled and must be validated against the session .
- Forms get progressive enhancement; event handlers do not. A form with a Server Action works before JavaScript loads. An event handler requires the client bundle. Choose the form path when the mutation is a submission, and the event handler path when it is an interaction .
- Serialization is strict. Functions, class instances, and React elements cannot cross the boundary. The return value should contain only the fields the UI needs, not raw database records .
- Server Functions are for mutations, not data fetching. React explicitly recommends against using them for reads. Fetch data in Server Components and mutate with Server Functions .
Remember: The "use server" directive is the thinnest possible wrapper around a network boundary. It does not validate, authenticate, authorize, or sanitize. It only makes the function callable. Everything that makes the call safe must be written inside the function, by you, every time. A Server Function without an auth check is not a shortcut—it is an open door. Treat every "use server" function as if it were a public API route, because it is.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!