Sub topic 13
Server Functions and the reverse direction
This chapter assumes you know the basics of React components, useState, async/await, and the "use client" boundary. It also assumes you have read how the RSC payload carries client references from the server to the browser. Here you will look at the opposite direction: how the browser calls code that lives on the server.
The problem: data flows one way
So far, data in the RSC model flows from server to client. The server renders a tree, serializes it into the payload, and the browser applies it. That covers reading data. Most apps also need to write data: save a form, delete a row, log in.
Without Server Functions, you would write an API route, call it with fetch from a Client Component, parse the response, and update the UI by hand. Server Functions replace much of that glue. You write an async function that runs on the server, and the client calls it as if it were a local function.
What a Server Function is
A Server Function is an async function that runs on the server and that client code can invoke over the network. You mark it with the "use server" directive.
The directive can go in two places:
- At the top of a module. Every exported function in that file becomes a Server Function.
- At the top of a single async function body, inside a Server Component. That one function becomes a Server Function.
// app/actions.js
'use server';
export async function addPost(formData) {
const title = formData.get('title');
if (typeof title !== 'string' || title.length === 0) {
throw new Error('Invalid title');
}
// save the post to a database here
}// app/NewPost.js (Server Component)
import { addPost } from './actions';
export default function NewPost() {
return (
<form action={addPost}>
<input name="title" />
<button type="submit">Add</button>
</form>
);
}When a form's action prop receives a function, React calls that function on submit and passes it a FormData object built from the form fields. Because addPost is a Server Function, the call goes to the server.
You will often see the term Server Action. A Server Action is a Server Function that is passed to a form action or called inside a transition. The two names describe the same mechanism. This chapter uses "Server Function" for the function itself.
<br>
What the client actually receives
The client never gets the function body. This follows the same idea as client references, but reversed.
When the bundler processes a "use server" module, it replaces the function in the client build with a server reference. A server reference is a small object that holds an identifier for the function, and not its code. The identifier usually combines a module id and an export name. Frameworks often encrypt or hash it.
Calling that reference on the client does the following:
- The client serializes the arguments.
- It sends an HTTP request (typically a
POST) to the framework's server endpoint, carrying the function identifier and the serialized arguments. - The server looks up the function by identifier and runs it.
- The server serializes the return value, and often a fresh RSC payload, and sends it back.
- The client applies the result.
The payload that returns from a Server Function call is the key to the reverse direction. After a mutation, the framework can re-render the affected Server Components and send the new tree back in the same response. The client applies it using the same process as navigation, so client state in unaffected Client Components survives.
Calling Server Functions from Client Components
A Client Component cannot define a Server Function, because its module runs in the browser. It can import one from a "use server" module, or receive one as a prop from a Server Component.
// app/LikeButton.js
'use client';
import { useTransition } from 'react';
import { likePost } from './actions';
export default function LikeButton({ postId }) {
const [isPending, startTransition] = useTransition();
return (
<button
disabled={isPending}
onClick={() => {
startTransition(async () => {
await likePost(postId);
});
}}
>
{isPending ? 'Saving...' : 'Like'}
</button>
);
}// app/actions.js
'use server';
export async function likePost(postId) {
if (typeof postId !== 'number') {
throw new Error('Invalid post id');
}
// update the database here
}Calling inside startTransition keeps the UI responsive and gives you isPending. Without a transition, the call still works, but you lose that pending state.
Server references are serializable, so a Server Component can pass one as a prop to a Client Component. This is the one kind of function that may cross the boundary in that direction. Ordinary functions, such as inline event handlers, still cannot.
Closures and bound arguments
A Server Function defined inline inside a Server Component can read variables from the surrounding scope.
// app/DeleteButton.js (Server Component)
export default function DeleteButton({ postId }) {
async function remove() {
'use server';
// postId is captured from the closure
console.log('deleting', postId);
}
return (
<form action={remove}>
<button type="submit">Delete</button>
</form>
);
}The captured values have to reach the server when the function is called, so the framework serializes them and attaches them to the server reference. Frameworks typically encrypt these values so the client cannot read or tamper with them. Even so, treat captured values as client-visible in your threat model unless your framework documents otherwise. Check the documentation of your framework for the exact guarantees.
Another option is bind, which makes the sent value explicit:
// app/actions.js
'use server';
export async function deletePost(postId, formData) {
if (typeof postId !== 'number') {
throw new Error('Invalid post id');
}
// delete the post here
}// app/DeleteButton.js (Server Component)
import { deletePost } from './actions';
export default function DeleteButton({ postId }) {
const deleteThisPost = deletePost.bind(null, postId);
return (
<form action={deleteThisPost}>
<button type="submit">Delete</button>
</form>
);
}Serialization works both ways
The rules from the earlier chapter on serializable props apply to arguments and return values as well. Arguments are serialized in the browser and deserialized on the server, and the return value travels back.
| Value | Can be an argument or return value |
|---|---|
| Strings, numbers, booleans, `null`, `undefined` | Yes |
| Plain objects and arrays of serializable values | Yes |
| `FormData` | Yes (as an argument) |
| `Date`, `Map`, `Set`, `BigInt`, typed arrays | Yes in current React versions |
| Promises | Yes |
| Server references | Yes |
| Class instances, functions that are not server references, symbols | No |
The exact list depends on the React version, so check the documentation for yours. A failed serialization throws an error at call time.
Security: treat every call as a public request
This is the most important point in the chapter. A Server Function is a network endpoint. Anyone who can reach your server can try to call it, with any arguments, even if your UI never shows a button for it.
Three consequences follow:
- Validate all input. Arguments come from the network, so TypeScript types or a React prop type say nothing about what arrives. Check types, ranges and lengths on the server, ideally with a schema library.
- Check authorization inside every function. Hiding a button is not access control. Verify the user's session and permissions in the function itself.
- Do not return more than needed. The return value reaches the browser. Do not send whole database rows with fields such as password hashes or internal notes.
Also remember that an unused exported function in a "use server" file can still be reachable. Some frameworks remove unused ones at build time, but you should not depend on that. Put only functions that are meant to be public in such files, and keep internal helpers in separate modules without the directive.
Common errors
- Putting
"use server"in a Client Component file. The directive in a file that also has"use client"conflicts. Keep Server Functions in their own module. - Defining an inline Server Function in a Client Component. Inline
"use server"functions are only valid inside Server Components. In a Client Component, import from a separate file. - Passing a normal function from server to client. Only server references may cross. Mark the function with
"use server", or move the handler into the Client Component. - Expecting synchronous behavior. Server Functions are always async from the client's view, even if you declare them without
asyncin some setups. Useawaitor a transition. - Assuming sequential execution. Frameworks may queue calls from one client, but different clients call in parallel. Do not rely on call order for correctness. Use database transactions where it matters.
Summary of the reverse direction
The RSC model has two channels. Rendering sends payloads from server to client. Server Functions send serialized calls from client to server, and the server usually answers with a result plus an updated payload. Both rely on references, not code, to cross the boundary: client references point at client modules, and server references point at server functions.
Exercise
A Server Component passes an inline arrow function () => console.log('hi') as an onClick prop to a Client Component, and the build fails. Give two ways to fix it, and say which one keeps the code running on the server.
Show answer
Option 1: move the handler into the Client Component, where it runs in the browser. Option 2: turn it into a Server Function (an async function with "use server") and pass that as the prop. Server references are serializable, so they can cross the boundary. Only option 2 runs on the server, and it must then validate its input and check authorization like any public endpoint.
Exercise
A form calls a Server Function deleteAccount(userId), where userId comes from a hidden input. The UI only shows the form to admins. Why is this unsafe, and what should the function do?
Show answer
Anyone can send a request to the function with any userId, regardless of what the UI shows. The function must validate that userId has the expected type, check the caller's session on the server, confirm the caller is allowed to delete that account, and only then act. It should not trust the hidden input or the fact that the button was hidden.