A form backed by a Server Action has to answer four questions: where do validation errors go, how does the user's input survive a failed submit, what does the UI show while the request is in flight, and what happens on success. React's useActionState answers the first three with one piece of state returned by the server, and Next.js's redirect answers the fourth. Nothing extra is needed on the client.
This walkthrough builds an invoice form with an email, a due date and a list of line items. The flat fields are easy. The line items are where most examples stop and real forms start: nested field errors, rows the user can add and remove, and input that has to stay attached to the right row.
The shape of the state
useActionState(action, initialState) returns [state, formAction, isPending]. When you pass formAction to a form, React calls your action with the previous state and the submitted FormData, and whatever the action returns becomes the new state. The useActionState reference adds two details that matter here: calls are queued and run in order, and when the action is a Server Function, the initial state and return value have to be serialisable.
So the state is plain data:
errors: messages keyed by field name, plus aformkey for errors that don't belong to one field.values: what the user submitted, as strings, so the inputs can be refilled.rows: the line-item row IDs in submitted order. More on why below.
Keying errors by the input's name is the decision everything else rests on. The component never has to translate between the schema's idea of a field and the DOM's: state.errors[name] is the error for the input with that name.
Validation with Zod
The schema lives in its own module so it can be unit tested without Next.js:
import { z } from 'zod'
const LineItem = z.object({
description: z.string().trim().min(1, 'Describe the item'),
quantity: z.coerce.number({ error: 'Enter a number' }).int('Whole numbers only').min(1, 'At least 1'),
unitPrice: z.coerce.number({ error: 'Enter a price' }).positive('Must be more than 0'),
})
export const InvoiceSchema = z.object({
customerEmail: z.email('Enter a valid email address'),
dueDate: z.iso.date('Pick a due date'),
items: z.array(LineItem).min(1, 'Add at least one line item'),
})
export type FieldErrors = Record<string, string[]>
export function readInvoiceForm(formData: FormData) {
const values: Record<string, string> = {}
const rows: string[] = []
const items: Record<string, string>[] = []
for (const [key, value] of formData) {
if (typeof value !== 'string' || key.startsWith('$ACTION')) continue
values[key] = value
const match = /^items\.([\w-]+)\.(description|quantity|unitPrice)$/.exec(key)
if (!match) continue
let index = rows.indexOf(match[1])
if (index === -1) index = rows.push(match[1]) - 1
;(items[index] ??= {})[match[2]] = value
}
return {
values,
rows,
input: { customerEmail: values.customerEmail, dueDate: values.dueDate, items },
}
}
export function errorsByField(error: z.ZodError, rows: string[]): FieldErrors {
const errors: FieldErrors = {}
for (const issue of error.issues) {
const path = issue.path.map((segment, i) =>
i === 1 && issue.path[0] === 'items' && typeof segment === 'number' ? rows[segment] : String(segment),
)
const key = path.length > 0 ? path.join('.') : 'form'
;(errors[key] ??= []).push(issue.message)
}
return errors
}Every value in FormData is a string, so the numbers use z.coerce.number(). An empty quantity coerces to 0 and fails min(1), which gives a better message than a type error. Text like abc coerces to NaN, which fails the type check and gets the custom "Enter a price" message from the error option. This is Zod 4 syntax: the Next.js forms guide still shows the older invalid_type_error option, and the Zod 4 changelog says that option was dropped in favour of error. The changelog also deprecates z.string().email() in favour of z.email(), and error.flatten() in favour of top-level functions.
Why not use z.flattenError() for the field errors? It's the right tool for a flat form, but it only keeps the top-level key. I ran it against a schema with an array of numbers, and the error for b[0] came back under b. For line items that means "something in items is wrong" with no way to tell which row or field. z.treeifyError() keeps the nesting, but then the component has to walk a tree. Joining each issue's path with dots gives keys like items.b2.quantity that match input names directly, which is simpler than either. The Zod error formatting docs describe both built-in shapes if you'd rather use one.
readInvoiceForm skips keys starting with $ACTION. Next.js adds hidden inputs with those names to forms that call Server Actions, and the forms guide warns that Object.fromEntries(formData) will include them. You don't want them echoed back into values.
Why rows have IDs instead of indexes
The obvious naming scheme is items.0.description, items.1.description. My first version of this form used it, and a component test caught the bug: submit two rows with an error, remove the first row, and the remaining row shows the first row's text.
Here's why. After the failed submit, React resets the form and each input takes its value from defaultValue, which comes from state.values. Removing row 0 re-renders the surviving row with index 0, so its name becomes items.0.description and its defaultValue becomes whatever row 0 contained. Since the input hadn't been edited since the reset, it shows that new default. The user's second line item now says what the first one said.
Naming fields by a stable row ID fixes it: items.first.description, items.4c1e….description. The server reads rows in the order they appear in FormData (which is document order), builds the array Zod validates, and maps the numeric index in each error path back to the row ID. The first row's ID is the fixed string first, not a random UUID, because a random value would differ between the server render and hydration and produce a hydration mismatch on the name attribute. Rows added later are created in a click handler, where crypto.randomUUID() is fine.
The Server Action
'use server'
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
import { requireUser } from '@/lib/auth'
import { saveInvoice } from '@/lib/invoices'
import { errorsByField, InvoiceSchema, readInvoiceForm, type FieldErrors } from './schema'
export type InvoiceFormState = {
errors: FieldErrors
values: Record<string, string>
rows: string[]
}
export async function createInvoice(_previous: InvoiceFormState, formData: FormData): Promise<InvoiceFormState> {
const user = await requireUser()
const { values, rows, input } = readInvoiceForm(formData)
const parsed = InvoiceSchema.safeParse(input)
if (!parsed.success) {
return { errors: errorsByField(parsed.error, rows), values, rows }
}
let invoiceId: string
try {
const invoice = await saveInvoice({ ...parsed.data, ownerId: user.id })
invoiceId = invoice.id
} catch {
return { errors: { form: ['We couldn’t save the invoice. Please try again.'] }, values, rows }
}
revalidatePath('/invoices')
redirect(`/invoices/${invoiceId}`)
}Three things in there are deliberate.
The auth check comes first. A Server Action is a public POST endpoint, whatever page renders the form. The Next.js forms guide says to verify authentication and authorisation inside every Server Action, even if the form only appears on an authenticated page. requireUser is your own helper; it should throw or redirect when there's no session.
Expected failures return state; they don't throw. A validation failure or a failed save returns an errors object and the submitted values. If the action threw instead, React would send the error to the nearest error boundary and replace the form with a fallback, taking the user's input with it.
redirect is called outside the try block. The redirect reference explains that it works by throwing a NEXT_REDIRECT error. Call it inside the try and the catch swallows it: the invoice saves, and the user sees "We couldn't save the invoice." That's why the ID is captured in a variable and the redirect happens after the block. revalidatePath runs first so the invoice list isn't stale when they get there. The return type is still Promise<InvoiceFormState> because redirect is typed never.
The form component
'use client'
import { useActionState, useState } from 'react'
import { createInvoice, type InvoiceFormState } from '../actions'
const initialState: InvoiceFormState = { errors: {}, values: {}, rows: [] }
function FieldError({ name, errors }: { name: string; errors: InvoiceFormState['errors'] }) {
const messages = errors[name]
if (!messages?.length) return null
return (
<p id={`${name}-error`} className="field-error">
{messages[0]}
</p>
)
}
export function InvoiceForm() {
const [state, formAction, pending] = useActionState(createInvoice, initialState)
const [rows, setRows] = useState<string[]>(() => (state.rows.length > 0 ? state.rows : ['first']))
const field = (name: string) => ({
id: name,
name,
defaultValue: state.values[name] ?? '',
'aria-invalid': state.errors[name] ? true : undefined,
'aria-describedby': state.errors[name] ? `${name}-error` : undefined,
})
return (
<form action={formAction} noValidate>
{state.errors.form && <p role="alert">{state.errors.form[0]}</p>}
<label htmlFor="customerEmail">Customer email</label>
<input type="email" {...field('customerEmail')} />
<FieldError name="customerEmail" errors={state.errors} />
<label htmlFor="dueDate">Due date</label>
<input type="date" {...field('dueDate')} />
<FieldError name="dueDate" errors={state.errors} />
<fieldset>
<legend>Line items</legend>
<FieldError name="items" errors={state.errors} />
{rows.map((rowId, index) => (
<div key={rowId} className="line-item">
<label htmlFor={`items.${rowId}.description`}>Description</label>
<input {...field(`items.${rowId}.description`)} />
<FieldError name={`items.${rowId}.description`} errors={state.errors} />
<label htmlFor={`items.${rowId}.quantity`}>Quantity</label>
<input inputMode="numeric" {...field(`items.${rowId}.quantity`)} />
<FieldError name={`items.${rowId}.quantity`} errors={state.errors} />
<label htmlFor={`items.${rowId}.unitPrice`}>Unit price</label>
<input inputMode="decimal" {...field(`items.${rowId}.unitPrice`)} />
<FieldError name={`items.${rowId}.unitPrice`} errors={state.errors} />
<button type="button" onClick={() => setRows(rows.filter((id) => id !== rowId))}>
Remove line {index + 1}
</button>
</div>
))}
<button type="button" onClick={() => setRows([...rows, crypto.randomUUID()])}>
Add line item
</button>
</fieldset>
<button type="submit" disabled={pending}>
{pending ? 'Saving…' : 'Create invoice'}
</button>
</form>
)
}The page itself stays a Server Component that renders <InvoiceForm />. Only the form needs 'use client', because of the hooks.
The field helper gives each input its name, its defaultValue from the last submission, and, when there's an error, aria-invalid and aria-describedby pointing at the message. A screen reader announces the error when the user tabs into the field, not just a red border.
Preserving input relies on documented reset behaviour. When a form action completes, React resets the uncontrolled fields to their defaults, and the form reference says React applies updated defaults before that reset. Because the new state.values arrives in the same update, the fields reset to what the user typed. On success the redirect navigates away, so there's nothing to clear.
The submit button reads pending from useActionState. Disabling it matters more here than in a chat box: two quick clicks would create two invoices. The queueing in useActionState means a second dispatch waits for the first rather than racing it, but it still runs. noValidate turns off the browser's built-in validation bubbles so the server's messages are the only ones the user sees. Drop it if you'd like the browser to catch an empty email before the round trip; the server validates either way.
It works before JavaScript loads
Because the form's action is a Server Action, the server-rendered HTML is a real <form method="POST" encType="multipart/form-data"> with the action's ID in hidden inputs. I ran a production build, fetched the page with curl, and posted the form back with the hidden fields and bad values, which is what a browser does when JavaScript hasn't loaded or failed. The response was the same page with all four field errors rendered and the inputs filled with what was submitted. A valid post came back as 303 with a Location of the new invoice, which matches the redirect docs: progressive-enhancement submits get a 303 so the browser follows with a GET.
The Add and Remove buttons need JavaScript, so a no-JS user gets one line item. That's an acceptable degradation for most apps. If it isn't, render a few empty rows server-side and have the schema ignore rows where every field is blank.
Testing it
The schema and parser are plain functions, so they get plain unit tests:
import { expect, it } from 'vitest'
import { errorsByField, InvoiceSchema, readInvoiceForm } from '../n204/app/invoices/schema'
function form(entries: Record<string, string>) {
const fd = new FormData()
for (const [k, v] of Object.entries(entries)) fd.append(k, v)
fd.append('$ACTION_KEY', 'ignored')
return fd
}
it('keys errors by the same dotted name the input uses', () => {
const { input, values, rows } = readInvoiceForm(form({
customerEmail: 'x', dueDate: '2026-02-30',
'items.a1.description': 'ok', 'items.a1.quantity': '1', 'items.a1.unitPrice': '5',
'items.b2.description': ' ', 'items.b2.quantity': '1.5', 'items.b2.unitPrice': '-1',
}))
expect(values.$ACTION_KEY).toBeUndefined()
const r = InvoiceSchema.safeParse(input)
expect(r.success).toBe(false)
if (!r.success) {
const e = errorsByField(r.error, rows)
console.log(JSON.stringify(e))
expect(Object.keys(e).sort()).toEqual(['customerEmail', 'dueDate', 'items.b2.description', 'items.b2.quantity', 'items.b2.unitPrice'])
}
})
it('reports an empty list on the items key', () => {
const r = InvoiceSchema.safeParse(readInvoiceForm(form({ customerEmail: 'a@b.co', dueDate: '2026-12-31' })).input)
expect(!r.success && errorsByField(r.error, [])).toEqual({ items: ['Add at least one line item'] })
})
it('coerces valid strings', () => {
const r = InvoiceSchema.parse(readInvoiceForm(form({ customerEmail: 'a@b.co', dueDate: '2026-12-31', 'items.x.description': ' Design ', 'items.x.quantity': '2', 'items.x.unitPrice': '150.5' })).input)
expect(r.items[0]).toEqual({ description: 'Design', quantity: 2, unitPrice: 150.5 })
})The component test mocks the action module, which lets you hold the request open and check the pending state, then resolve it and check that values, errors and ARIA wiring all land. That's the test that caught the index-naming bug. End-to-end behaviour, including the no-JS path, is worth one Playwright test that disables JavaScript and submits the form.
When this pattern doesn't fit
Server-only validation means a round trip before the user sees any error. For long forms, add client-side checks for the obvious cases (required fields, email format) and keep the server as the authority. You can run the same Zod schema in the browser, but don't let it replace the server check.
If the form is a search or filter that should update as the user types, a Server Action is the wrong tool; that state belongs in the URL. And if you want the result to appear before the server confirms it, as in a comment thread, that's optimistic UI, which form submissions with transitions and useOptimistic covers. For whether a mutation belongs in a Server Action or a Route Handler in the first place, see the boundary between Route Handlers and Server Actions. If two users can edit the same record, read Server Action concurrency and stale data before you ship.













