React Server Components (Part 5): Server Functions and Mutations
Use React Server Functions safely for mutations. Learn use server, validation, authorization, optimistic UI, concurrency, errors, revalidation and when an API is still the better tool.

React Server Functions can make a mutation look almost suspiciously simple.
A Client Component can call an async function whose implementation runs on the server. A form can submit directly to one. The framework handles the network bridge.
That removes plumbing. It does not remove the network, the trust boundary, authentication, authorization, validation, concurrency or failure modes.
The most important rule in this entire article is therefore simple:
Treat every Server Function callable from the client as a public server endpoint.
What use server actually means
React’s 'use server' directive marks async functions that can be called from client-side code.
It does not mark a Server Component. There is no 'use server' directive for Server Components themselves.
You can define a Server Function inside a Server Component:
export default async function AccountPage() {
async function updateName(formData: FormData) {
'use server'
// mutation
}
return <form action={updateName}>{/* ... */}</form>
}
Or put callable functions in a server module:
'use server'
export async function updateName(formData: FormData) {
// mutation
}
A Client Component can then import the framework-generated reference rather than receiving the implementation itself.
Server Function versus Server Action
Current React terminology distinguishes the two.
Server Function is the general term for a server-side function exposed through this mechanism.
A Server Action is a Server Function used as an action — for example when passed to a form’s action prop.
Older articles often call every 'use server' function a Server Action. You will still encounter that terminology in framework documentation and existing codebases.
The arguments are attacker-controlled
This is where the abstraction can fool people.
Consider:
'use server'
export async function deleteProject(projectId: string) {
await db.project.delete({ where: { id: projectId } })
}
The fact that your UI only renders a Delete button beside projects owned by the current user proves nothing about the request reaching this function.
A caller can manipulate client state and request payloads.
The function must establish identity and authorization on the server:
'use server'
export async function deleteProject(projectId: string) {
const session = await requireSession()
const project = await db.project.findUnique({
where: { id: projectId },
select: { id: true, ownerId: true },
})
if (!project || project.ownerId !== session.user.id) {
throw new Error('Not found')
}
await db.project.delete({ where: { id: project.id } })
}
Authentication answers who are you? Authorization answers may you perform this operation on this resource? You normally need both.
Validate everything crossing the boundary
TypeScript types disappear at runtime.
This signature:
async function updateQuantity(productId: string, quantity: number)
does not prove that a malicious request supplied a valid product ID or sensible numeric quantity.
Validate server-side:
const quantity = Number(formData.get('quantity'))
if (!Number.isInteger(quantity) || quantity < 1 || quantity > 100) {
return { ok: false, error: 'Choose a quantity between 1 and 100.' }
}
For complex inputs, use a runtime schema validator or equivalent domain validation rather than scattering weak casts throughout the action.
Forms are a natural fit
Server Actions integrate particularly well with forms because a form already represents a mutation request.
async function createTask(formData: FormData) {
'use server'
const session = await requireSession()
const title = String(formData.get('title') ?? '').trim()
if (title.length < 2 || title.length > 120) {
return { error: 'Enter a title between 2 and 120 characters.' }
}
await db.task.create({
data: { title, ownerId: session.user.id },
})
}
This can reduce client-side request boilerplate substantially.
It also supports progressive-enhancement patterns in frameworks that integrate Server Actions with forms.
Do not use Server Functions as your general read API
React’s current guidance describes Server Functions primarily as mutation mechanisms. They are not recommended as a generic data-fetching layer.
Frameworks may queue action execution, and the result is not designed around the caching behaviour you want for normal reads.
Fetch ordinary page data in Server Components. Use browser-side query libraries or API endpoints where client-side reads are genuinely needed.
Return expected errors; throw unexpected ones
A validation error is not the same kind of event as a database outage.
Expected result:
return {
ok: false,
fieldErrors: {
email: 'That email address is already registered.'
}
}
Unexpected failure:
throw new Error('Database unavailable')
The first belongs in normal UI flow. The second belongs in your error boundary, server logs and monitoring.
Do not dump raw exception text into the browser just because it is easy to return from the function.
Revalidate after a successful mutation
If a mutation changes cached data, the user should not submit successfully and then continue seeing the old value.
A robust mutation sequence often looks like:
- authenticate;
- validate input;
- authorize the resource operation;
- perform the transaction;
- invalidate/revalidate affected cached data;
- redirect or return the new UI state.
The exact invalidation API belongs to the framework. The responsibility belongs to your mutation.
Transactions still matter
A Server Function is not a database transaction.
If placing an order must:
- reserve inventory;
- create an order;
- record payment state;
- write an audit event;
then the same consistency rules apply as they would behind a REST or GraphQL endpoint.
Use transactional boundaries appropriate to the datastore and business process. Think about retries and idempotency for operations that can be submitted more than once.
Double submission is a real problem
Users double-click. Networks retry. Browsers reconnect. Payment providers call webhooks more than once.
For high-value operations, design explicit idempotency rather than assuming one UI click means one server invocation.
An idempotency key can allow the server to recognise that two requests represent the same intended operation.
Optimistic UI is a prediction
React can make a mutation feel immediate by updating the interface optimistically before the server confirms success.
That is excellent for reversible, low-risk interactions such as toggling a favourite or adding a lightweight item to a list.
It is less appropriate when pretending success would be materially misleading — for example confirming a financial transfer before the server has accepted it.
Optimistic state needs a failure story. If the mutation is rejected, the UI must reconcile with authoritative server state and explain what happened.
Concurrency needs domain rules
Two administrators can edit the same record. Two customers can attempt to buy the last item.
RSC does not solve lost updates.
Depending on the domain, use mechanisms such as:
- database constraints;
- row/version tokens;
- optimistic concurrency checks;
- atomic update statements;
- serializable transactions where justified;
- inventory reservation workflows.
The action should fail safely when its assumptions are no longer true.
CSRF and framework protections
Frameworks can provide important protections around Server Action transport, allowed origins and request handling. Use them, configure them correctly, and keep the framework patched.
But do not translate “the framework has CSRF protections” into “this mutation no longer needs authorization.” They solve different problems.
A valid request from your own origin can still attempt an object the current user does not own.
Secrets can still leak through return values
The function executes on the server, but its arguments and returned values cross a serialization boundary when called from the client.
Do not return a full ORM entity simply because it is already available.
Return the minimum client-facing shape:
return {
ok: true,
project: {
id: project.id,
name: project.name,
},
}
Keep internal flags, tokens, hashes, private notes and infrastructure metadata out of the serialized result.
When an explicit API is better
Server Functions are excellent for application-internal mutations tightly coupled to a React UI.
Use an explicit HTTP/API surface when the capability also needs to serve:
- mobile applications;
- external customers;
- webhooks;
- partner integrations;
- non-React clients;
- independently versioned services;
- public API consumers.
Do not force every backend capability through a React-specific transport because the first caller happened to be a web form.
Observability
A production mutation should be traceable.
Useful telemetry can include:
- operation name;
- request/correlation ID;
- authenticated actor ID where policy permits;
- affected resource ID;
- duration;
- validation rejection counts;
- authorization failures;
- database or dependency errors;
- idempotency outcome;
- cache invalidation outcome.
Do not log passwords, session tokens, complete form bodies or other sensitive values simply because action arguments are convenient to serialize.
Server-side does not automatically mean secure
Use SiteTidy alongside application-level review to catch exposed headers, client assets and other production configuration problems.
Production checklist
For every client-callable Server Function:
- authenticate on the server where required;
- authorize the specific operation and resource;
- validate runtime input;
- treat IDs and hidden fields as attacker-controlled;
- return only necessary serializable data;
- distinguish expected validation failures from system errors;
- use transactions where the domain requires atomicity;
- design idempotency for retry-sensitive operations;
- define concurrency behaviour;
- revalidate affected cached state after success;
- log safely without recording secrets;
- keep React/framework RSC packages patched.
The principle to keep
Server Functions remove a layer of ceremony between React UI and server mutation code. They do not remove the server boundary.
If anything, the nicer syntax makes discipline more important because a remote operation can look deceptively like an ordinary local function call.
Design it like an endpoint even when React lets you write it like a function.
