Capítulo 113 de 116

Chapter 113: 'use server'

Core Idea

'use server' is the directive that actually defines a Server Function (Ch 111) — placed at the top of a function or a module, it's the mechanism that makes a piece of server-only logic callable from client code across the network boundary.

Key Concepts

  • Two placements: at the top of an individual async function (marking just that one function as a Server Function), or at the top of a whole module (marking every export from that file as a Server Function) — mirroring 'use client''s file-vs-function scoping options.
  • Must be an async function: since calling it from the client is inherently a network round-trip, a Server Function marked this way is always awaited by its caller.
  • Distinct from 'use client''s direction: 'use client' (Ch 112) marks a rendering boundary (components that must execute in the browser); 'use server' marks a callable-function boundary in the opposite direction (server-only logic invokable from client code) — the two directives solve related but distinct problems in the RSC model.
  • Never executes on the client: even though it's called from client code, the function body itself always runs server-side — only the call (with serializable arguments) and the returned result cross the network.
  • Same serialization and untrusted-input rules as covered in Ch 111 apply here, since this directive is the literal mechanism that chapter describes.

Code Examples

async function deletePost(postId) {
  'use server';
  await db.posts.delete(postId);
}
  • What it demonstrates: a single function-scoped 'use server' directive, defining a Server Function inline rather than marking a whole module.

Key Takeaways

  1. Function-level 'use server' is for a one-off Server Function inline in a file that's otherwise ordinary (possibly client) code; module-level is for a dedicated actions file where every export is server-only.
  2. Always async — the call is inherently asynchronous once it crosses the client/server boundary.
  3. Think of 'use client' and 'use server' as marking opposite-direction boundaries in the same RSC architecture, not as competing or redundant mechanisms.

Connects To

  • Ch 111 (Server Functions): the full behavioral treatment of what this directive enables.
  • Ch 112 ('use client'): the opposite-direction boundary directive.