Course map
Stage 1: App Router Foundations
Stage 2: The Rendering Model
Stage 3: Data, Caching and Mutations
Stage 4: Full-Stack Next.js
Stage 5: Production and Specialization

Part 12 / Stage 3

Server Actions and forms

Goal: Mutate data the Next.js way — a 'use server' function invoked directly from a <form action={...}>, with no hand-written fetch, no client-side API route, and no JavaScript required for the basic case to work at all. Built on Udupi Grande's review form and its menu's stock toggle — the same running example Part 11 used to invalidate a cache; this part is where the mutation that triggers that invalidation actually gets written. Time: ~7 h · Level: finished Part 11 (revalidateTag, updateTag, on-demand revalidation) Verified against: Next.js 16.4.6 / React 19.3.0, cacheComponents: true + partialPrefetching: true — this install's defaults since create-next-app, confirmed in TOOLING.md.

What you will learn

  • 'use server': the directive that turns a function into a Server Function, and the two legal places to put it (inline inside a Server Component's own body, or at the top of a whole file)
  • <form action={serverFunction}>: React's own extension of the HTML form element, and the real, byte-for-byte hidden fields it renders so the form keeps working with no client-side JavaScript loaded at all
  • useActionState: managing pending state and returning validation errors from the server, with no client-side fetch call anywhere
  • useFormStatus: why it has to live in its own component, nested inside the <form>, not in the component that renders the <form> itself
  • Why every Server Action is a public POST endpoint the moment it exists in a client bundle, and what this install's own framework-level protections do and don't cover
  • Choosing updateTag for read-your-own-writes inside a Server Action — the same call Part 11 could only describe from the outside, now built and exercised directly
  • useOptimistic + useTransition: making a 500ms-plus mutation feel instant, and proving, with a real timed request, exactly how much latency the optimistic update is actually hiding

Topics in this part

Practice

Every exercise adds a scratch route under harness/app/mandi/scratch-greet/, runs a real command against it, and then removes what it added. Copy the exact commands you ran and their real output into your own notes; do not type output from memory.

A note on reading a hidden $ACTION_* field: the exact field names and values are different for every build (and every action's own shape — an action with no bound arguments and no useActionState gets a simpler $ACTION_ID_... field; one with bound arguments or action state gets the $ACTION_REF_n/$ACTION_n:0/$ACTION_n:1 triplet Part 12's README shows). Always read the real values out of your own curl output — never reuse the ones printed in this file, they belong to a different build.


Exercise 1: The simplest possible Server Action, inline

Scenario: Part 12's README builds two file-level 'use server' actions, both imported into Client Components. Build the other legal form — an inline action, directly inside a Server Component, with no Client Component and no hook anywhere. What to do: Create app/mandi/scratch-greet/page.tsx with a Server Component whose own function body defines async function greet(formData) { "use server"; ... } and renders <form action={greet}>. Read the real hidden field it produces, then resubmit it with curl.

Sample output (run for real against this course's harness):

$ curl -s http://localhost:PORT/mandi/scratch-greet | grep -o '<form.\{0,200\}'
<form action="" encType="multipart/form-data" method="POST"><input type="hidden" name="$ACTION_ID_4036898a47001f1a920607d1bd1dc69cffa0141a00"/><input type="text" name="name"/><button type="submit">Greet</button></form>
$ curl -s -X POST http://localhost:PORT/mandi/scratch-greet -F '$ACTION_ID_4036898a47001f1a920607d1bd1dc69cffa0141a00=' -F 'name=Priya'

Server log:

GreetPage action ran for: Priya

💡 Hint: Notice the hidden field shape here ($ACTION_ID_<id>, one field, no value) is simpler than the review form's ($ACTION_REF_n + two numbered fields + $ACTION_KEY) — this action has no bound arguments and no useActionState wrapping it, so there's nothing extra to serialize.


Exercise 2: .bind() — an argument that isn't a form field at all

Scenario: forms.md's own documented pattern for passing a value the form itself never collects. What to do: Create app/mandi/scratch-greet/with-bind/page.tsx. Write async function greetWithRole(role, formData) { "use server"; ... }, bind it with greetWithRole.bind(null, "staff"), and use the bound function as the form's action. Read the hidden fields and resubmit with curl.

Sample output (run for real against this course's harness):

$ curl -s http://localhost:PORT/mandi/scratch-greet/with-bind | grep -o '<form.\{0,350\}'
<form action="" encType="multipart/form-data" method="POST"><input type="hidden" name="$ACTION_REF_0"/><input type="hidden" name="$ACTION_0:1" value="[&quot;staff&quot;]"/><input type="hidden" name="$ACTION_0:0" value="{&quot;id&quot;:&quot;...&quot;,&quot;bound&quot;:&quot;$@1&quot;}"/><input type="text" name="name"/>...

Server log after resubmitting with the real name field plus the three hidden fields above:

GreetWithRole action ran for: Deepa (staff)

💡 Hint: "staff" is sitting in that hidden field in plain text — exactly the installed forms.md guide's own warning about hidden-input alternatives: bound arguments become part of the rendered HTML and are not encoded. Never .bind() a secret.


Exercise 3: The default 1MB Server Action body limit, hit for real

Scenario: Section 5's security note mentions a "1MB default body size limit" in passing. Trigger it. What to do: POST a multipart body with a single field over 1MB to any existing Server Action route (app/mandi/scratch-greet from Exercise 1 works fine) and read the real error.

Sample output (run for real against this course's harness, using a 1.5MB field value):

$ python3 -c "... POST a 1.5MB 'comment' field to /mandi/scratch-greet ..."
status: 500

Server log:

⨯ Error: Body exceeded 1 MB limit.
To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit
    at ignore-listed frames {
  statusCode: 413
}

💡 Hint: The error's own internal statusCode is 413 (Payload Too Large) even though the response the client actually sees is a generic 500 — and the error message names the exact config (serverActions.bodySizeLimit) to raise the limit, if a real use case needs to.


Exercise 4: The real CSRF rejection, triggered with a mismatched Origin

Scenario: Section 5 names a CSRF check comparing Origin to Host. Trigger the actual rejection. What to do: POST to any Server Action route (Exercise 1's scratch-greet works) with an explicit, wrong Origin header.

Sample output (run for real against this course's harness):

$ curl -s -D - -X POST http://localhost:PORT/mandi/scratch-greet \
  -H "Origin: https://evil-attacker.example" \
  -F '$ACTION_ID_...=' -F 'name=Mallory'
HTTP/1.1 500 Internal Server Error

Server log:

`x-forwarded-host` header with value `localhost:PORT` does not match `origin` header with value `evil-attacker.example` from a forwarded Server Actions request. Aborting the action.
⨯ Error: Invalid Server Actions request.

💡 Hint: Compare this against a curl request with no Origin header at all (what every plain curl command in this part's README actually sends) — that one only produces a warning (⚠ Missing origin header...) and still succeeds. A missing origin is tolerated; a wrong one is rejected outright. This is the CSRF check section 5 names, triggered from your own request instead of taken on faith.


Exercise 5: A garbage action id — not a CSRF problem, a different error entirely

Scenario: Distinguish "the origin doesn't match" (Exercise 4) from "this action simply doesn't exist" — two different failure modes with two different real error signatures. What to do: POST to app/mandi/scratch-greet with a syntactically plausible but entirely made-up action id.

Sample output (run for real against this course's harness):

$ curl -s -D - -X POST http://localhost:PORT/mandi/scratch-greet \
  -F '$ACTION_ID_0000000000000000000000000000000000000000=' -F 'name=Ghost'
HTTP/1.1 400 Bad Request
x-nextjs-action-not-found: 1

Response body:

Invalid Server Action request.

💡 Hint: 400, not 500, and a dedicated x-nextjs-action-not-found: 1 header — a distinct, more specific signal than Exercise 4's CSRF rejection. This is the real-world shape of the server-actions.md guide's deployment warning: "a client still running the previous build may invoke an action ID that no longer exists" after a rolling deploy rotates action ids — now reproduced on demand instead of waiting for a real deployment to hit it.


Next

🎉 Stage 3 done! Go to Stage 4: Full-Stack Next.js.

Show the solutions for Part 12 (5 files)

solutions/ex01.tsx

// Solution to Exercise 1. Drop in as harness/app/mandi/scratch-greet/page.tsx.
// Delete afterward - not part of the harness's canonical Part 12 state.
export default function GreetPage() {
  async function greet(formData: FormData) {
    "use server";
    const name = String(formData.get("name") ?? "stranger");
    console.log(`GreetPage action ran for: ${name}`);
  }

  return (
    <form action={greet}>
      <input type="text" name="name" />
      <button type="submit">Greet</button>
    </form>
  );
}

// $ curl -s http://localhost:PORT/mandi/scratch-greet | grep -o '<form.\{0,200\}'
// <form action="" encType="multipart/form-data" method="POST"><input type="hidden" name="$ACTION_ID_4036898a47001f1a920607d1bd1dc69cffa0141a00"/><input type="text" name="name"/><button type="submit">Greet</button></form>
// $ curl -s -X POST http://localhost:PORT/mandi/scratch-greet -F '$ACTION_ID_4036898a47001f1a920607d1bd1dc69cffa0141a00=' -F 'name=Priya'
// Server log: GreetPage action ran for: Priya
// Confirmed for real against this harness: a plain curl multipart POST,
// with the exact hidden field copied from the real server-rendered HTML,
// reached this inline Server Action with no JavaScript at all. Note the
// simpler hidden-field shape vs. the review form's ($ACTION_REF_n +
// $ACTION_n:0/:1 + $ACTION_KEY) - this action has no bound args and no
// useActionState, so there's nothing extra to serialize.

solutions/ex02.tsx

// Solution to Exercise 2. Drop in as harness/app/mandi/scratch-greet/with-bind/page.tsx.
// Delete afterward.
async function greetWithRole(role: string, formData: FormData) {
  "use server";
  const name = String(formData.get("name") ?? "stranger");
  console.log(`GreetWithRole action ran for: ${name} (${role})`);
}

export default function GreetWithBindPage() {
  const greetAsStaff = greetWithRole.bind(null, "staff");
  return (
    <form action={greetAsStaff}>
      <input type="text" name="name" />
      <button type="submit">Greet as staff</button>
    </form>
  );
}

// $ curl -s http://localhost:PORT/mandi/scratch-greet/with-bind | grep -o '<form.\{0,350\}'
// <form action="" encType="multipart/form-data" method="POST"><input type="hidden" name="$ACTION_REF_0"/><input type="hidden" name="$ACTION_0:1" value="[&quot;staff&quot;]"/><input type="hidden" name="$ACTION_0:0" value="{&quot;id&quot;:&quot;...&quot;,&quot;bound&quot;:&quot;$@1&quot;}"/><input type="text" name="name"/>...
// $ curl -s -X POST http://localhost:PORT/mandi/scratch-greet/with-bind \
//   -F '$ACTION_REF_0=' -F '$ACTION_0:1=["staff"]' \
//   -F '$ACTION_0:0={"id":"<the real id from the HTML above>","bound":"$@1"}' \
//   -F 'name=Deepa'
// Server log: GreetWithRole action ran for: Deepa (staff)
// Confirmed for real against this harness: "staff" - the bound argument -
// is sitting in plain text inside a hidden input, exactly the installed
// forms.md guide's own warning: bound arguments become part of the
// rendered HTML and are not encoded. Never bind a secret this way.

solutions/ex03.md

# Solution to Exercise 3

Uses Exercise 1's `app/mandi/scratch-greet/page.tsx` route as-is — no new
route file needed, only an oversized request.

**Script, run for real against this harness** (Python standard library only,
so the request is built by hand rather than relying on a tool that might
cap body size itself):
```python
import urllib.request

boundary = "xBOUNDARYx"
big = "A" * (1024 * 1024 + 500 * 1024)  # 1.5MB - comfortably over the 1MB default
body = (
    f"--{boundary}\r\n"
    'Content-Disposition: form-data; name="comment"\r\n\r\n'
    f"{big}\r\n"
    f"--{boundary}--\r\n"
).encode()
req = urllib.request.Request(
    "http://localhost:PORT/mandi/scratch-greet",
    data=body,
    headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
    method="POST",
)
try:
    with urllib.request.urlopen(req) as resp:
        print("status:", resp.status)
except urllib.error.HTTPError as e:
    print("status:", e.code)
    print("body:", e.read().decode(errors="replace")[:300])
```

**Real output:**
```text
status: 500
body: Internal Server Error
```

**Real server log, same request:**
```text
⨯ Error: Body exceeded 1 MB limit.
To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit
    at ignore-listed frames {
  statusCode: 413
}
```

The client sees a generic `500`, but the error thrown internally carries
`statusCode: 413` (Payload Too Large) and names the exact fix —
`serverActions.bodySizeLimit` in `next.config.ts` — for any real use case
that genuinely needs to accept a larger payload (a file upload, for
instance). This is this install's own enforcement of the limit
`server-actions.md`'s security section names in passing; this exercise is
what actually triggers it.

solutions/ex04.md

# Solution to Exercise 4

Uses Exercise 1's `app/mandi/scratch-greet/page.tsx` route as-is — the only
difference from a normal submission is one extra header.

**Request, run for real against this harness** (the real action id read
from that build's own HTML, same as Exercise 1):
```text
$ curl -s -D - -X POST http://localhost:PORT/mandi/scratch-greet \
  -H "Origin: https://evil-attacker.example" \
  -F '$ACTION_ID_4036898a47001f1a920607d1bd1dc69cffa0141a00=' \
  -F 'name=Mallory'
HTTP/1.1 500 Internal Server Error
```

**Real server log:**
```text
`x-forwarded-host` header with value `localhost:PORT` does not match `origin` header with value `evil-attacker.example` from a forwarded Server Actions request. Aborting the action.
⨯ Error: Invalid Server Actions request.
```

**Contrast — the exact same request with NO `Origin` header at all**
(every plain `curl` command elsewhere in this part's README and examples):
```text
$ curl -s -X POST http://localhost:PORT/mandi/scratch-greet \
  -F '$ACTION_ID_4036898a47001f1a920607d1bd1dc69cffa0141a00=' \
  -F 'name=Priya'
```
```text
⚠ Missing `origin` header from a forwarded Server Actions request.
GreetPage action ran for: Priya
```

A **missing** `Origin` only produces a warning and the action still runs —
`curl` never sends an `Origin` header by default, which is exactly why every
other `curl` example in this course's Server Actions content works without
ever setting one. A **present but wrong** `Origin` is rejected outright,
with the server comparing it against `x-forwarded-host`/`Host` and aborting
the moment they don't match. This is the real CSRF check `server-actions.md`'s
security section names (`allowedOrigins`, for legitimately different
proxy/CDN domains, is the configuration escape hatch for cases where the
origin genuinely should differ from the host).

solutions/ex05.md

# Solution to Exercise 5

Uses Exercise 1's `app/mandi/scratch-greet/page.tsx` route as-is, with a
deliberately fabricated action id instead of the real one.

**Request, run for real against this harness:**
```text
$ curl -s -D - -X POST http://localhost:PORT/mandi/scratch-greet \
  -F '$ACTION_ID_0000000000000000000000000000000000000000=' \
  -F 'name=Ghost'
HTTP/1.1 400 Bad Request
x-nextjs-action-not-found: 1
content-type: text/plain
```

**Response body:**
```text
Invalid Server Action request.
```

**Contrast with Exercise 4's result:**

| | Mismatched `Origin` (Ex. 4) | Garbage action id (Ex. 5) |
|---|---|---|
| Status | `500` | `400` |
| Distinguishing header | none beyond the standard ones | `x-nextjs-action-not-found: 1` |
| Server log | names the origin/host mismatch directly | no server-side console log at all — the id never resolved to a real action to run |

These are two genuinely different failure modes with two different real
signatures, not the same error dressed up two ways: Exercise 4's request
*would* have reached a real action if the origin had matched; Exercise 5's
request never names a real action in the first place. This is the everyday,
on-purpose version of the scenario `server-actions.md`'s deployment section
warns about for real traffic: *"New deployments typically generate new
[action] IDs... so a client still running the previous build may invoke an
action ID that no longer exists. The error surfaces as 'Failed to find
Server Action'."* A stale client after a rolling deploy produces exactly
this `400` / `x-nextjs-action-not-found` pair, not a crash and not a silent
failure — which is also why that same guide recommends surfacing it in the
UI as a retry path rather than a hard failure.

Common mistakes

Mistake Why it is wrong Fix
Putting a plain type or constant inside a file-level 'use server' module Every export of that file becomes a Server Function reference — a non-function export doesn't fit that contract Keep shared types/constants (like ReviewFormState) in their own directive-free file, imported by both sides
Assuming a Server Action needs a logged-in session check only if the UI happens to gate it behind a login page Render-time gating isn't a security boundary — section 2's curl command reached the action directly, bypassing the page entirely Authenticate and authorize inside every action, every time, per the installed server-actions.md guide
Calling useFormStatus in the same component that renders the <form> The hook only reports the nearest parent form's status — there's no parent form yet at that point, verified in section 4 Put the status-reading code in a separate component, nested inside the <form>
Expecting updateTag to work from a Route Handler It's Server-Action-only (Part 11 already reproduced the real error) Use revalidateTag(tag, { expire: 0 }) outside a Server Action, updateTag only inside one
Treating useOptimistic's value update as if it eliminates the server round trip It only changes what's rendered during the wait — the real 527ms round trip still happens, measured directly in section 7 Use it for perceived responsiveness, not as a substitute for making the actual mutation faster
Forgetting that useActionState's echoed values are what make a failed form keep showing what the user typed Without echoing the submitted values back in the returned state, a failed validation re-render would reset uncontrolled fields to empty Return { errors, values } from the action, and wire defaultValue={state.values.x} on every field

Quick recap

  • 'use server' marks a Server Function; file-level marks every export, inline marks one function in a Server Component's own body — this part uses the file-level form for both of its actions, each in its own file by purpose.
  • <form action={...}> genuinely works with no JavaScript loaded — its hidden $ACTION_* fields were read directly from a real response and resubmitted with plain curl, reaching the real Server Action and getting the real redirect.
  • useActionState turns an action's return value into the next render's state — validation errors and the submitted values both come back in one response, with no separate client-side fetch.
  • useFormStatus must be called from a component nested inside the <form>, not the component rendering the form itself — verified against the installed forms.md guide's own stated reason.
  • Every Server Action is a public POST endpoint, reachable with a plain curl command with no session — framework-level protections exist, but application-level authentication/authorization is this part's (and the installed docs') explicit, non-optional responsibility.
  • updateTag, called inside a Server Action, lands in the same HTTP response (x-action-revalidated: 1, a real header) — the read-your-own-writes guarantee Part 11 could only describe, now built and measured.
  • useOptimistic + useTransition make a real 527ms Server Action round trip (measured directly, not estimated) feel instant — without changing how long that round trip actually takes.

Checklist

  • I read a real server-rendered form's hidden $ACTION_* fields and resubmitted them with curl, reaching the Server Action with no JavaScript involved at all.
  • I submitted invalid data to a Server Action wired through useActionState and got validation errors back in the same response, with no separate client fetch.
  • I can explain, from the installed docs' own wording, why useFormStatus has to be called from a component nested inside the <form>.
  • I can state why "the form is only rendered on an authenticated page" is not a security boundary for a Server Action.
  • I called a Server Action that uses updateTag and read a real x-action-revalidated: 1 header confirming the re-render happened in the same response.
  • I measured a real Server Action's round-trip time directly (not estimated) and can state exactly what latency a useOptimistic update on that same action is hiding.

Search the guide