← All topics

Server Actions & mutations

Functions marked 'use server' that run on the server and can be passed straight to <form action>.

  • Forms work before hydration (progressive enhancement) and get automatic reset after the action.
  • useActionState gives you returned state (validation errors) plus a pending flag.
  • useOptimistic shows the expected result instantly while the action runs.
  • After a write call revalidatePath (or a tag) so the UI refetches. redirect() ends the action and navigates.
  • after() from next/server schedules work (logging, analytics) after the response is sent.
  • Always re-check authorization inside the action: it is a public POST endpoint.

See it in this app: src/app/actions.ts, src/components/add-task-form.tsx, src/components/task-list.tsx

"use server";
export async function addTask(projectId: string, _prev: FormState, fd: FormData) {
  await requireUser();
  db.addTask(projectId, String(fd.get("title")), "medium");
  revalidatePath("/projects/" + projectId);
  return { ok: true };
}