Server Functions

Calling the server from a form, and securing the endpoint.

Builds on Server Components, Actions.

The last chapter ended with one exception to "functions can't cross the boundary": a function marked "use server" can be passed to the client, because what crosses isn't the function but a way to call it. That's a Server Function, and it closes the loop. Server Components move reads to the server; Server Functions move writes there.

You already know the client half. In Actions you passed async functions to <form action>, tracked them with useActionState and showed optimistic results with useOptimistic. This chapter swaps those client functions for server ones, and then spends most of its time on the part that matters in production: a Server Function is a public HTTP endpoint, and it has to be secured like one.

The problem: an endpoint for every button#

Without Server Functions, adding a book to the reading list from a server-rendered page takes three pieces: the form, a client handler that calls fetch, and an API route. Each one has to agree with the others on the URL, the method, the body shape and the error format.

AddBook.tsx
"use client";

export function AddBook() {
  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const res = await fetch("/api/books", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ title: new FormData(e.currentTarget).get("title") }),
    });
    if (!res.ok) alert("Failed");
    // ...and now refetch the list somehow
  }
  return (
    <form onSubmit={onSubmit}>
      <input name="title" />
      <button>Add</button>
    </form>
  );
}

It works, but nothing connects these files except strings, the form is dead until JavaScript loads (preventDefault needs JS), and updating the page after the write is left as an exercise.

"use server"#

A Server Function is an async function marked with the "use server" directive. There are two places to put it.

At the top of a function body, inside a Server Component, to define one inline:

app/books/page.tsx
import { db } from "@/lib/db";

export default async function Page() {
  const books = await db.book.findMany();

  async function addBook(formData: FormData) {
    "use server";
    await db.book.create({ data: { title: String(formData.get("title")) } });
  }

  return (
    <>
      <ul>{books.map((b) => <li key={b.id}>{b.title}</li>)}</ul>
      <form action={addBook}>
        <input name="title" />
        <button>Add</button>
      </form>
    </>
  );
}

At the top of a file, to make every export a Server Function that can be imported anywhere, including from client components:

app/actions.ts
"use server";

import { db } from "@/lib/db";

export async function addBook(formData: FormData) {
  await db.book.create({ data: { title: String(formData.get("title")) } });
}

The rules from react.dev: the directive must come first, before imports (comments are fine), in single or double quotes, not backticks. It can only mark async functions, since the network call is always asynchronous. It only works in server-side files. To import a Server Function into client code, the directive has to be at module level.

Note what "use server" is not: it's not the opposite of "use client". You don't mark Server Components with it. Server Components are the default; "use server" marks functions the client is allowed to call.

Server Functions, Server Actions: the names#

React's docs are precise about this: until September 2024, React called all of these "Server Actions". It now calls them Server Functions, and a Server Function becomes a Server Action when it's passed to an action prop or called from inside an Action. So every Server Action is a Server Function, but not every Server Function is a Server Action. Next.js's docs and most of the ecosystem still say "Server Actions" for the common case, so expect both words in an interview and know the distinction.

What a call actually is#

The magic is a build step. When the bundler sees "use server", it keeps the function body in the server bundle and registers it under an id. Client code that imports the function gets a stub instead: a function that serializes its arguments and POSTs them to the server with that id. The server looks up the function, decodes the arguments, runs it, and sends back the return value, and frameworks add fresh Server Component output for the page in the same response.

What a Server Function call really is
BrowserServernetworkaddBook = ref("a1f9")client bundle: no function body<form action={addBook}>waiting for the useruseActionStatestate: nullactions.ts: addBook()registered as a1f9decode args (untrusted)FormData from the requestauth → validate → writeinside the function
Step 1 of 5

At build time the bundler finds "use server". The function body stays in the server bundle. The client bundle gets only a reference: an id and a small function that knows how to call it.

You can't run a framework server in this sandbox, so here's a simulation with the same moving parts in one page: a pretend server with a registry and a session, the generated client stub, and a real useActionState form. The server.js and client-runtime.js files play the framework's role. Add a book, try an empty title, then press the forged-request button.

Server Functions, simulated
import { useActionState } from "react";
import { createServerReference } from "./client-runtime.js";
import { handlePost, encodeArgs } from "./server.js";
import "./actions.js"; // in a real app this module never reaches the browser

// What `import { addBook } from "./actions"` gives a client component: a stub.
const addBook = createServerReference("actions#addBook");

export default function App() {
  const [state, formAction, isPending] = useActionState(addBook, null);
  return (
    <>
      <form action={formAction}>
        <input name="title" placeholder="Book title" />
        <button disabled={isPending}>{isPending ? "Adding..." : "Add"}</button>
      </form>
      {state?.error && <p style={{ color: "#a0461f" }}>{state.error}</p>}
      {state?.ok && <p>Added "{state.book.title}" (id {state.book.id})</p>}
      <hr />
      <button onClick={forge}>Send a forged delete as mallory</button>
    </>
  );
}

// Anyone can hit the endpoint directly. No form, no React, someone else's cookie.
async function forge() {
  const res = await handlePost({ actionId: "actions#deleteBook", body: encodeArgs([1]), cookieUser: "mallory" });
  console.log("Forged request →", res.status, res.body);
}
Nothing logged yet.

The console shows each "request": an action id and the encoded FormData. The forged delete fails with Forbidden, not because the UI hid the button, but because deleteBook checked ownership itself. Delete that check and the forged request succeeds. Hold on to that; it's the second half of the chapter.

Calling Server Functions from forms#

Pass a Server Function to <form action> and React calls it with the submitted FormData. Or put one on a specific button with formAction, so one form can have "Save" and "Delete" buttons that call different functions. Server Functions passed to action or formAction run inside a transition automatically, and when one succeeds React resets the form's uncontrolled fields.

Progressive enhancement#

Because the form's action refers to something the server can resolve by itself, a form rendered with a Server Function can be submitted before the JavaScript bundle loads. The browser does a normal form POST, the framework runs the function, and the response renders the result. Once JavaScript is there, the same form submits without a page reload. That's progressive enhancement: the page works on a slow phone or with a failed script, and gets better when JavaScript arrives. The client-side Actions from Part 4 can't do this, since their function lives only in the bundle.

useActionState with a Server Function#

useActionState works with Server Functions exactly as with client Actions, with one shape to remember: the function receives the previous state first and the FormData second, and its return value becomes the new state.

app/actions.ts
"use server";

import { z } from "zod";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { refresh } from "next/cache";

const BookInput = z.object({ title: z.string().trim().min(1).max(120) });

export async function addBook(prevState: { error?: string } | null, formData: FormData) {
  const user = await requireUser(); // throws or redirects if signed out
  const parsed = BookInput.safeParse({ title: formData.get("title") });
  if (!parsed.success) return { error: "Title must be 1 to 120 characters." };

  await db.book.create({ data: { title: parsed.data.title, ownerId: user.id } });
  refresh(); // Next.js 16: refresh the page's Server Component output
  return { error: undefined };
}

With a Server Function, users can submit before hydration finishes and React can show the returned state before JavaScript loads. The optional third argument, "/books", is the permalink: if the form is submitted before the bundle loads, the browser navigates to that URL, and if that page renders the same form with the same Server Function, React passes the returned state to it. Use it when the form can appear on pages other than the one its result should show on.

How the page refreshes after the write is framework territory. In Next.js 16 it's refresh(), updateTag() or revalidatePath() inside the function, covered in Data and mutations in Next.js.

Calling Server Functions from client code#

You can also import a Server Function into a client component and call it like any async function, for example from an event handler. React's guidance is to call it inside a transition (startTransition or useTransition), so you get a pending state and it composes with other Actions:

LikeButton.tsx
"use client";

import { useTransition, useOptimistic } from "react";
import { likeBook } from "./actions";

export function LikeButton({ bookId, likes }: { bookId: number; likes: number }) {
  const [isPending, startTransition] = useTransition();
  const [optimisticLikes, addOptimistic] = useOptimistic(likes, (n, delta: number) => n + delta);

  return (
    <button
      disabled={isPending}
      onClick={() =>
        startTransition(async () => {
          addOptimistic(1);
          await likeBook(bookId);
        })
      }
    >
      Like ({optimisticLikes})
    </button>
  );
}

Two limits from the react.dev reference worth repeating in an interview:

  • Server Functions are for mutations, not reads. Frameworks typically process one action at a time and don't cache return values. Fetch data in Server Components (or with a query library), not by calling a Server Function in an effect.
  • Arguments and return values must be serializable, with the same rules as props crossing to the client (functions other than Server Functions, class instances and JSX can't be arguments). FormData is supported as an argument.

Closures and bound arguments#

An inline Server Function inside a Server Component can use variables from the component's scope:

app/books/[id]/page.tsx
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const version = await getVersion(id);

  async function publish() {
    "use server";
    // `id` and `version` were captured when the page rendered.
    if (version !== (await getVersion(id))) throw new Error("Changed since you opened it");
    await publishBook(id);
  }

  return <form action={publish}><button>Publish</button></form>;
}

Think about where version lives. The server rendered the page and finished; the function runs in a later request. So the captured values are sent to the client with the reference and come back with the call. Next.js encrypts closed-over variables with a per-build key so the client can't read or forge them, and its docs still say not to rely on encryption alone for sensitive values. You can also pass extra arguments explicitly with fn.bind(null, id). Either way, assume anything that round-trips through the browser can be inspected or replayed, and re-check permissions inside the function.

Server Functions are public endpoints#

This is the part that matters most. Every Server Function the client can reach is an HTTP endpoint. There's no route file, so it doesn't look like one in code review, and that's exactly the danger. Anyone can call it with any arguments, as the forged request above showed. The UI showing or hiding a button is not access control.

The react.dev reference says it plainly: arguments to Server Functions are fully client-controlled, so treat them as untrusted input, and in every Server Function check that the logged-in user is allowed to perform that action. A checklist for every one you write:

  1. Authenticate inside the function. A redirect in the page that renders the form doesn't protect the function; it's a separate entry point. Read the session again.
  2. Authorize the specific resource. Being logged in isn't permission to delete this book. Check ownership or role against the id you were given, or you've written an IDOR (insecure direct object reference) bug.
  3. Validate every argument. Types, lengths, ranges, enums. formData.get("title") can be a File, null or a 5 MB string. A schema library like Zod makes this one line.
  4. Return only what the UI needs. Return values are serialized to the client. Returning the database row returns every column.
  5. Rate-limit expensive or abusable ones (sending email, sign-up, anything that costs money), keyed by user or IP.
  6. Keep the logic in a data access layer. Put the auth checks and queries in a server-only module that every Server Function and Server Component calls, so a forgotten check in one action can't skip them.

Frameworks add defense in depth, and it's worth knowing what Next.js does: Server Actions only accept POST, and Next compares the Origin header to the host to block cross-site requests (CSRF), with experimental.serverActions.allowedOrigins for proxies. Action ids are encrypted, non-deterministic and recalculated between builds, and Server Actions your code never uses are removed from the build so they don't become endpoints. None of that replaces the checklist: a valid id is easy to find in the client bundle.

Fix itLock down the reading list actions

These Server Functions work fine through the UI. They're also wide open. Fix actions.js so that:

  • Signed-out callers can't add books.
  • Titles must be strings of 1 to 120 characters after trimming.
  • A user can delete only books they own (ownerId).

The hidden checks call the endpoint directly, as different users, the way an attacker would.

"use server";

import { db } from "./db.js";
import { getSession, registerServerFunction } from "./server.js";

export async function addBook(prevState, formData) {
  const session = getSession();
  const title = formData.get("title");
  const book = { id: db.nextId++, title, ownerId: session?.userId ?? "anonymous" };
  db.books.push(book);
  return { ok: true, book: { id: book.id, title: book.title } };
}

export async function deleteBook(id) {
  const book = db.books.find((b) => b.id === Number(id));
  if (!book) return { ok: false };
  db.books.splice(db.books.indexOf(book), 1);
  return { ok: true };
}

registerServerFunction("actions#addBook", addBook);
registerServerFunction("actions#deleteBook", deleteBook);
Nothing logged yet.

Keeping server code on the server#

Server Functions and Server Components make it easy to blur where code runs. Two tools keep the line sharp.

The server-only package. Add import "server-only" at the top of any module that must never be bundled for the browser: the data access layer, anything that reads secrets from process.env. If a client module imports it, directly or through a chain of imports, the build fails instead of shipping your database code. (Next.js handles the import internally; installing the npm package keeps linters happy.) Its twin client-only does the reverse for browser-only modules.

Taint APIs Experimental. React has two experimental APIs, available only in the experimental channel and only inside Server Components, that make React throw if a specific value or object is passed to the client:

lib/data.ts
import "server-only";
import { experimental_taintObjectReference, experimental_taintUniqueValue } from "react";

export async function getUser(id: string) {
  const user = await db.user.findUnique({ where: { id } });
  // The whole object must never be passed to a client component.
  experimental_taintObjectReference("Don't pass the full user record to the client.", user);
  // Nor this specific token, for as long as `user` is alive.
  experimental_taintUniqueValue("Don't send the session token to the client.", user, user.sessionToken);
  return user;
}

experimental_taintObjectReference(message, object) blocks that exact object. experimental_taintUniqueValue(message, lifetime, value) blocks a high-entropy string, bigint or typed array (a token, a key) for as long as the lifetime object exists. Next.js enables them with experimental.taint: true. They're a safety net, not a security boundary: a copy, a substring, an uppercase version or a base64 encoding of a tainted value isn't tainted. Filter data in the data access layer first.

A real lesson: React2Shell (December 2025)#

On December 3, 2025, the React team disclosed CVE-2025-55182, rated critical with a CVSS score of 10.0: unauthenticated remote code execution. The flaw was in how React decodes payloads sent to Server Function endpoints. A crafted HTTP request to any Server Function endpoint could make the deserializer execute code on the server. It became known as React2Shell.

The details are the lesson:

  • It was in the framework, not in app code. It affected the react-server-dom-webpack, react-server-dom-parcel and react-server-dom-turbopack packages, versions 19.0, 19.1.0, 19.1.1 and 19.2.0, and through them Next.js, React Router, Waku, @parcel/rsc, @vitejs/plugin-rsc and RedwoodSDK. Apps were vulnerable even if they didn't define any Server Functions, as long as they supported Server Components.
  • Next.js tracked it as CVE-2025-66478 for App Router apps on Next.js 15.x, 16.x and 14.3 canaries (Pages Router apps and Next.js 13 and 14 stable weren't affected). There was no workaround; the fix was upgrading (React 19.0.1, 19.1.2, 19.2.1 and matching Next.js patch releases), and Next.js advised rotating secrets for apps that were online and unpatched.
  • It was exploited quickly, and the follow-ups kept coming: on December 11 the React team disclosed denial-of-service bugs (CVE-2025-55184, then CVE-2025-67779 because the first fix was incomplete) and a source code exposure bug (CVE-2025-55183) that could return a Server Function's source, including secrets hardcoded in it. Another denial-of-service fix (CVE-2026-23864) followed in January 2026. Teams that patched once had to patch again.

What to take from it, and what to say when an interviewer asks:

  1. Deserialization is attack surface. Server Functions accept a rich serialization format from anyone on the internet. Every endpoint that parses untrusted input needs the same scrutiny, and you inherit the framework's parser.
  2. Patch fast, and keep patching. Have a process for security releases: watch the React and Next.js blogs and GitHub advisories, keep lockfiles current with automated update PRs, and be able to deploy a dependency bump in hours, not weeks.
  3. Assume breach after exposure. Rotate secrets if you ran a vulnerable version on the public internet. Don't hardcode secrets in source; read them from the environment (the source exposure bug couldn't reveal runtime process.env values).
  4. Defense in depth still matters. WAF rules from hosting providers helped while people patched, but both React and Next.js said not to rely on them.

Pitfalls#

Check your understanding#

PredictIs this protected?
export default async function AdminPage() {
  const session = await auth();
  if (!session?.user.isAdmin) redirect("/login");

  async function deleteAll() {
    "use server";
    await db.book.deleteMany();
  }

  return <form action={deleteAll}><button>Delete everything</button></form>;
}

A non-admin never sees this page. Can a non-admin delete every book?

Quick checkServer Function or Server Action?

According to react.dev's current terminology, which statement is accurate?

Explain it out loudHow do you secure Server Functions?

An interviewer asks: "Server Actions look like normal functions. What do you have to think about to make them secure?"

Explain it out loudProgressive enhancement

An interviewer asks: "What does progressive enhancement mean for forms that use Server Functions, and why can't a client-side Action do the same?"

Interview angle

Say it in 30 seconds

A Server Function is an async function marked "use server" that client code can call. The bundler keeps its body on the server and gives the client a reference: calling it sends a POST with an action id and the serialized arguments, the server runs the function and returns the result, and frameworks send fresh Server Component output in the same round trip. Passed to a form's action, it works before JavaScript loads. The catch is that every Server Function is a public HTTP endpoint, so each one must authenticate, authorize the specific resource, validate its arguments and return minimal data, and the framework that decodes those requests must be kept patched.

What is a Server Function, and how does calling one work?

basic

What's the difference between a Server Function and a Server Action?

basic

How do you secure Server Functions?

senior

What does progressive enhancement mean for Server Functions?

intermediate

What happens to variables captured by an inline Server Function?

senior

What was the December 2025 React Server Components vulnerability, and what's the lesson?

senior

What are React's taint APIs and how much should you rely on them?

intermediate

Recap#

  • "use server" marks async functions the client may call: inline in a Server Component, or at the top of a module so its exports can be imported by client code. It's not a directive for Server Components.
  • React calls them Server Functions; one passed to action or called inside an Action is a Server Action. Next.js still mostly says Server Actions.
  • A call is a POST with an action id and serialized arguments; the server runs the function and returns the result (plus fresh RSC output in frameworks). Forms with Server Functions work before JavaScript loads, and useActionState receives (prevState, formData) with an optional permalink.
  • Every Server Function is a public endpoint: authenticate, authorize the resource, validate arguments, return minimal data and rate-limit, ideally through a server-only data access layer. Closed-over values round-trip through the client (Next.js encrypts them).
  • Taint APIs (experimental) are a safety net, not a boundary. React2Shell (CVE-2025-55182, Next.js CVE-2025-66478) showed the payload decoder itself is attack surface: patch quickly and rotate secrets after exposure.

Sources#