Defining. 'use server' goes at the top of an async function body or of a module. At module level, every export becomes a Server Function, importable even from client code; inline in a Server Component, the function is passed down as a prop. Only async functions qualify, because every call crosses the network.
What the client gets is a reference: an id (module plus export name) and any bound arguments, never the code. React on the client turns it into an async function. Calling it:
- encodes the arguments with
encodeReply, in the RSC format withFormDataadded and JSX not allowed; - hands the id and encoded arguments to the
callServerfunction the framework supplied, so the transport (URL, headers) is the framework's; - on the server,
decodeReplyrebuilds the arguments, the framework looks up the function by id and runs it, and the return value is serialized like a prop and decoded on the client as the promise's result.
Where to call it. Pass it to <form action> or formAction (it runs in a Transition, gets the FormData, and the form can submit before JavaScript loads) or to useActionState; elsewhere, call it inside startTransition. Server Functions are for mutations. The docs advise against using them to fetch data: frameworks typically process one call at a time and don't cache results.
What it exposes. Each Server Function is a public server endpoint. In the docs' words, arguments "are fully client-controlled": anyone can send any id with any arguments, without your UI. So inside the function, validate every argument, check the logged-in user may perform this action, and escape output. The return value goes to the client, so return only what it needs. Values bound with .bind, or captured by an inline Server Function, travel through the client too.