# Server Actions in Forms — Next.js

Source: https://www.skillbyai.com/en/nextjs/m-action

> A form action that runs on the server.

## "use server" functions

A **Server Action** (Server Function) is an async function marked with `"use server"`, either inline in a Server Component or in a separate file. Pass it to a form's `action` prop and React submits the form data to the server, runs the function, and refreshes the UI. Forms work even before JavaScript loads (progressive enhancement). After writing data, call `revalidatePath` or `revalidateTag` so cached pages update, or `redirect` to another page.

## Forms that run on the server

Server Actions let forms and components call server code directly, with validation and revalidation.

![Three ideas: Server Actions, security, form UX.](assets/figures/nextjs/section-5-map.svg) — Figure 5.1 — Actions, security and form UX.

## A guestbook with a Server Action

This file is from a small demo store I built with Next.js 16.3.8, React 19.3 and TypeScript; `next build` compiled and type-checked it successfully. The inline action validates the name, stores it (in memory for the demo) and revalidates the page. In the build output the page is static; the action triggers revalidation when it runs. The action was compiled but not exercised with curl.

```tsx
import { revalidatePath } from "next/cache";

const entries: string[] = [];                    // demo only: in-memory, lost on restart

async function addEntry(formData: FormData) {
  "use server";
  const name = String(formData.get("name") ?? "").trim();
  if (name.length < 2) return;                   // always validate on the server
  entries.push(name);
  revalidatePath("/guestbook");
}

export default function GuestbookPage() {
  return (
    <section>
      <form action={addEntry}>
        <input name="name" placeholder="Your name" />
        <button type="submit">Sign</button>
      </form>
      <ul>{entries.map((e, i) => <li key={i}>{e}</li>)}</ul>
    </section>
  );
}
```

## Use a real database

The in-memory array is only for the demo; serverless and multi-instance deployments lose or split such state.

**Quiz:** What marks a function as a Server Action?

- [ ] Exporting it from next.config
- [ ] The "use client" directive
- [ ] Naming it action.js
- [x] The "use server" directive

*Answer:* The "use server" directive. Server Functions run on the server when called from the client.
