Forms and Server Actions
Build a mutation boundary that validates input, preserves user intent and returns useful pending, error and success states.
What you will be able to do
- Explain the network request behind a Server Action.
- Validate untrusted FormData before changing records.
- Wire accessible field errors and pending feedback.
- Choose an explicit freshness operation after a successful write.
Before this lesson
A function call still crosses a network
A form starts with intent: the reader wants to change a saved record. The browser cannot safely perform that database write itself. It sends a request containing untrusted values, and the server decides whether the caller may perform the operation. A Server Action gives that request a convenient React integration. It does not remove latency, retries, authorization, or database failure from the problem.
Keep three contracts separate. The input contract describes accepted fields and limits. The mutation contract describes the permitted state change. The response contract describes what the interface can show afterward. For an editable product name, a useful result contains field errors or a confirmed updated name, not a raw database exception. Define these shapes before building the button.
Narrow and validate at the boundary
FormData values can be strings or files and fields may be absent. A TypeScript assertion changes the compiler view without checking the received value. First narrow the runtime type, trim where the domain permits it, validate lengths and formats, and reject unexpected values. HTML required and maxLength attributes improve feedback but can be bypassed by a direct request.
The following validator is complete for its deliberately small contract. The action wrapper is an integration example: connect its server-only DAL to your own storage adapter. The authenticated identity must come from the server session. Do not trust a hidden ownerId field, and do not send password hashes or session tokens back in the result.
Shared application logic
export function parseName(value: unknown) {
if (typeof value !== "string") return { ok: false as const, error: "Enter a name" };
const name = value.trim();
if (name.length < 2 || name.length > 60) {
return { ok: false as const, error: "Use 2 to 60 characters" };
}
return { ok: true as const, name };
}Server execution
"use server";
import { updateTag } from "next/cache";
import { parseName } from "@/lib/product-input";
import { renameOwnedProduct } from "@/lib/product-dal";
type State = { error: string; message: string };
export async function renameProduct(previous: State, form: FormData): Promise<State> {
const parsed = parseName(form.get("name"));
if (!parsed.ok) return { error: parsed.error, message: "" };
const id = form.get("id");
if (typeof id !== "string") return { error: "Missing product", message: "" };
await renameOwnedProduct(id, parsed.name);
updateTag("products");
return { error: "", message: "Product saved" };
}Give every request a visible state
Use useActionState when the next interface depends on an action result. Its action receives the previous state before the form payload, a frequent source of incorrect parameter ordering. A pending state should communicate work without destroying the entered fields. Inline messages should be associated with their input, while a status region announces a successful save without moving focus unexpectedly.
Place useFormStatus in a component rendered inside the form whose state it observes. A hook in the same component that later returns the form is not inside that form context. Native form submission and a Server Action can support progressive enhancement, but still test the actual page with JavaScript disabled if that behavior is part of your requirements.
Separate validation, failure and navigation
An invalid name is an expected result. Return a typed validation response and keep the form available. An unavailable database is an unexpected failure that belongs in server logging and the route recovery path. A redirect is framework control flow, so place it after a successful operation instead of swallowing it inside a broad catch that converts every thrown value into a generic form error.
Confirm the write before invalidating its cache. A read-your-writes action can use updateTag, while background content publication may deliberately use stale-while-revalidate. Neither operation guarantees that a second independent browser tab instantly changes. Explain the exact visible promise: this submitter sees a confirmed value, and other readers refresh according to the selected cache policy.
Rebuild the complete interaction
Before opening the solution, write the states idle, pending, invalid, failed and saved on paper. Draw the allowed transitions and list which values survive each transition. Then implement the pure validator below, integrate it into a real action, and exercise it through the keyboard. Change the request payload manually to prove the server validates independently of the form.
In an interview, narrate one invariant at a time: only an authorized owner can rename; accepted names are normalized consistently; a rejected submission does not erase the draft; success appears only after the write completes. These statements guide test cases and explain why a form that looks correct in the happy path may still be incomplete.
Misconceptions to replace
Compare the tempting shortcut with the model you can verify in code.
- CLAIM TO CHALLENGEServer Actions are private because they look like ordinary functions.
- A more accurate model
They are callable network boundaries and must validate input and authorize the resource.
- How to check it
Next.js Server Actions and data-security guides; attempt a direct unauthorized action request.
- CLAIM TO CHALLENGEPending UI prevents every duplicate write.
- A more accurate model
It only represents one interface request; retries need server-side idempotency or constraints.
- How to check it
The lesson separates visible pending state from durable mutation identity.
Mistakes to catch in your own code
- Treating TypeScript casts as runtime validation.
- Assuming a disabled button prevents duplicate requests from other clients.
- Calling updateTag before the storage operation succeeds.
- Catching redirect control flow and replacing it with an error.
Write it by hand
JavaScript logic playground
Normalize and validate a product form
Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.
- Input is an object with name and price strings.
- Return {ok:false, errors} with name and/or price keys when invalid.
- Name must contain 2 to 60 characters after trimming. Price must use digits with at most two decimal places and represent 1 to 1000000 cents.
- On success return {ok:true, value:{name,priceCents}}. This kata checks input rules, not Server Action execution.
Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.
Inspect 4 test cases
- Normalize valid fields
Input
{ "name": " Notebook ", "price": "12.50" }Expected
{ "ok": true, "value": { "name": "Notebook", "priceCents": 1250 } } - Keep both field errors
Input
{ "name": "x", "price": "free" }Expected
{ "ok": false, "errors": { "name": "Use 2 to 60 characters", "price": "Enter 0.01 to 10000.00" } } - Reject extra precision
Input
{ "name": "Pen", "price": "1.234" }Expected
{ "ok": false, "errors": { "price": "Enter 0.01 to 10000.00" } } - Accept one cent
Input
{ "name": "Pin", "price": "0.01" }Expected
{ "ok": true, "value": { "name": "Pin", "priceCents": 1 } }
Reveal the worked solution and reasoning
function solve(input) {
const errors = {};
const name = typeof input.name === "string" ? input.name.trim() : "";
if (name.length < 2 || name.length > 60) errors.name = "Use 2 to 60 characters";
const price = typeof input.price === "string" ? input.price.trim() : "";
let cents = 0;
if (/^\d+(?:\.\d{1,2})?$/.test(price)) {
const parts = price.split(".");
cents = Number(parts[0]) * 100 + Number((parts[1] || "").padEnd(2, "0"));
}
if (!Number.isSafeInteger(cents) || cents < 1 || cents > 1000000) {
errors.price = "Enter 0.01 to 10000.00";
}
return Object.keys(errors).length ? { ok: false, errors } : { ok: true, value: { name, priceCents: cents } };
}Parse decimal text into integer cents instead of depending on binary floating-point multiplication for money.
Collect independent field errors in one pass so the user can correct the complete submission.
The bounded input contract is a learning example, not a universal international currency parser.
Verify it in a real Next.js application
Next.js application lab
Trace validation and idempotency in the task form
Open the local application route /dashboard after starting the workbench. Follow the experiment and collect the evidence described below.
Make the change
- Run the project, choose a practice identity at /login, and inspect components/task-form.tsx, createTask in app/actions.ts, and validateTaskTitle in lib/domain.ts. The shipped task contract trims a title and requires 3 to 80 characters.
- Submit three spaces to reach server validation even though the browser minLength check passes. Inspect the action response, linked feedback, retained input and unchanged task list. Then submit a valid title and observe the success message, cleared input and refreshed workspace.
- Inspect the hidden requestId and the tenant/user/request key recorded by createTask. In a separate test copy, replay one captured logical submission with the same title, then with a different title, and explain the distinct results.
- Implementation extension: add a second field and its own server validation plus accessible field message. Adapt the lesson parser to that new contract instead of replacing the existing task validator with a different field policy.
Check the behavior
- The server rejects whitespace-only or out-of-range titles before adding a task, and the submitted draft remains available after a validation error.
- A valid action creates one task and refreshes the workspace; the client pending button alone is not the idempotency mechanism.
- The same stored request key with the same title returns the existing result; reuse with changed input returns a conflict message without another task.
- The additional field is an implementation assignment. Its malformed direct submission must fail even when browser validation is bypassed.
Review the application reasoning
The inline kata verifies a pure parser. This project already implements a real Server Action, useActionState form and a single-process file-store idempotency example. Inspect actual requests to verify the boundary; a distributed transactional store remains an extension.
Open the project files and run instructions
A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.
The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.
cd nextjs-interview-lab
npm ci
npm run dev
# In a second terminal
npm test
# Stop dev, then verify the production application
npm run build
npm start
# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2eOpen http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.
Explain it in an interview
Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.
01When would you choose a Server Action over a Route Handler?
A Server Action fits a mutation closely coupled to React UI, including forms, pending feedback and an updated server-rendered view. A Route Handler is a clearer public HTTP contract for external clients, webhooks, or independently fetched resources.
I would decide from the callers and required protocol rather than the amount of code. Both boundaries still need input validation, authorization and failure handling. I would not use an action as a generic parallel GET transport.
Follow-up questions
- How would a mobile client invoke this feature?
- Which result should be an expected validation error?
- Mutating dataOfficial documentation
- Server Actions and mutationsOfficial documentation
- Route HandlersOfficial documentation
02Why validate again if the input already has required and maxLength?
The browser form is one possible caller. A request can be constructed without those controls, and FormData does not promise that a value is a string. Server validation establishes the actual mutation contract.
Client checks provide fast guidance. Server checks protect the invariant. I keep shared pure rules where appropriate while ensuring the server executes them independently.
Follow-up questions
- What happens when a File arrives instead of a name?
- Where should resource ownership be checked?
- Forms with Server ActionsOfficial documentation
- Data securityOfficial documentation
03How do pending state and duplicate-write protection differ?
Pending state tells the current interface that its request is in flight and can discourage repeated clicks. It does not coordinate another tab, a retry after a timeout, or another server instance.
If the operation must execute once, I use a durable idempotency contract or a database uniqueness constraint alongside the UI feedback. I also distinguish a timeout from proof that the write failed.
Follow-up questions
- What should the user see after a connection drops?
- Can the same request safely be retried?
- Server Actions and mutationsOfficial documentation
- Forms with Server ActionsOfficial documentation
04Does rendering a form only for an admin secure its action?
No. The action is a separate entry point. It must re-read the authenticated identity and check permission on the requested resource before the mutation.
The page check selects what UI is rendered. The data access check decides whether a write is permitted, including direct requests and permissions that changed since the page loaded.
Follow-up questions
- How would you test an unauthorized direct request?
- What if a user changes the hidden record ID?
- Data securityOfficial documentation
Check your understanding
Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.
Your checkpoint
Loading your local progress.
Sources and further reading
- Mutating dataOfficial documentation
- Server Actions and mutationsOfficial documentation
- Forms with Server ActionsOfficial documentation
- Data securityOfficial documentation
- updateTagOfficial documentation
- WAI form notificationsOfficial documentation