Capítulo 111 de 116

Chapter 111: Server Functions

Core Idea

Server Functions are functions marked 'use server' that a Client Component can call as if they were local — React handles serializing the call across the network, running it on the server, and returning the result, most commonly used as a form's action (Ch 97) or an event handler triggering server-side work.

Key Concepts

  • Defined with 'use server': placed at the top of a function (or a module, marking every export in it) to designate it as callable from the client but always executing on the server — the function body genuinely only runs server-side, never shipped to the browser.
  • Callable from Client Components despite running on the server — this is what makes them distinct from a plain Server Component: they're server-only behavior exposed to client-side interaction, not server-only rendering.
  • Common pairing with <form action={serverFunction}> (Ch 97): submitting the form calls the Server Function directly with FormData, with progressive enhancement (the browser can submit via a real HTTP request even before JS loads) as a direct consequence.
  • Arguments and return values must be serializable — plain objects, arrays, strings, numbers, and similar; a Server Function can't accept or return arbitrary class instances, functions, or other things that can't cross a network boundary as data.
  • Security implication: because a Server Function becomes a callable network endpoint, its arguments are attacker-controlled input, the same as any API route — validating/sanitizing them server-side is still necessary, "it's a function call in my code" doesn't remove that responsibility.

Code Examples

// actions.js
'use server';
export async function createPost(formData) {
  await db.posts.create({ title: formData.get('title') });
}

// Client Component
<form action={createPost}>
  <input name="title" />
</form>
  • What it demonstrates: a client-rendered form calling a server-only function directly via action, with the function's actual database logic never shipping to the browser.

Key Takeaways

  1. 'use server' marks a function as a client-callable, server-only network boundary — not just "runs on the server" but "is invokable from client code."
  2. Arguments crossing this boundary must be serializable — treat it like any RPC/API boundary in that respect.
  3. Treat Server Function inputs as untrusted, exactly like any API endpoint — the convenient calling syntax doesn't remove the need to validate.

Connects To

  • Ch 110 (Server Components): the sibling RSC concept for server-only rendering rather than callable behavior.
  • Ch 97 (<form>): the most common calling pattern for Server Functions.
  • Ch 113 ('use server'): the directive reference this chapter's mechanism is built on.