Next.js Forms: Validation and Progressive Enhancement


Forms are where a product asks a person to make something true: create an account, change a record, send a message, accept a cost. The browser, server, and interface each have a job in that exchange. A strong Next.js form starts with native semantics, treats all submitted values as untrusted, explains what is happening, and adds client behaviour only when it creates a better experience.
Progressive enhancement is not nostalgia for page reloads. It is an engineering discipline: the underlying action remains understandable and useful without an optimistic client layer, while JavaScript makes the same interaction faster and more expressive when it is available.
Start With a Complete HTML Form
The current Next.js forms guide (opens in new tab) uses the extended HTML action attribute to invoke a Server Action with FormData. That makes a simple server-rendered form a good baseline.
import { createContact } from "./actions";
export function ContactForm() {
return (
<form action={createContact}>
<label htmlFor="email">Work email</label>
<input
autoComplete="email"
id="email"
name="email"
required
type="email"
/>
<label htmlFor="message">How can we help?</label>
<textarea id="message" name="message" required rows={5} />
<button type="submit">Send message</button>
</form>
);
}Every field has a real name, associated label, useful input type, and a submit button. That is already usable with a keyboard, assistive technology, browser autofill, and ordinary HTTP form submission. It also gives client JavaScript a stable foundation rather than requiring a separate fetch protocol.
Progressive form-state explorer
Interactive guide: select a stage to see the responsibility the experience must cover.
Native form
Semantic labels and browser constraints supply the baseline submission path, even before client JavaScript loads.
Do not confuse a hidden input with security. It can carry context through a form, but its value is visible and editable. Load the authoritative resource and authorize the current actor inside the action, as the framework guidance requires for every Server Action.
Validate at Two Different Layers
Browser constraints such as required, type="email", minLength, and pattern give immediate, low-cost feedback. Keep them. They improve ordinary completion but are not enforcement: requests can be crafted, scripts can be disabled, and a valid-looking string may still violate a business rule.
Server validation parses FormData into an intentional command. It answers whether the submitted data is usable, bounded, and safe for the domain operation.
"use server";
import { z } from "zod";
const contactSchema = z.object({
email: z.string().trim().email().max(254),
message: z.string().trim().min(20).max(2_000),
});
export type ContactState =
| { status: "idle" }
| { status: "invalid"; errors: Record<string, string[]> }
| { status: "sent" };
export async function createContact(
_previous: ContactState,
formData: FormData
): Promise<ContactState> {
const parsed = contactSchema.safeParse({
email: formData.get("email"),
message: formData.get("message"),
});
if (!parsed.success)
return { status: "invalid", errors: parsed.error.flatten().fieldErrors };
await contacts.create(parsed.data);
return { status: "sent" };
}The server does more than schema validation: authenticate where needed, authorize the exact resource, normalize values, apply rate limits, and enforce domain rules such as “this address cannot create another pending invite.” Validation answers shape; authorization answers permission; neither replaces the other.
Return a Small Form-State Protocol
Expected failures should return a stable result the interface can render. Treat that return value as a small protocol, not as a raw copy of an exception or database result. The client needs field errors, a safe summary, and a success signal—not stack traces or internal policy details.
"use client";
import { useActionState } from "react";
import { createContact, type ContactState } from "./actions";
const initialState: ContactState = { status: "idle" };
export function EnhancedContactForm() {
const [state, action, pending] = useActionState(createContact, initialState);
const errors = state.status === "invalid" ? state.errors : {};
return (
<form action={action}>
<label htmlFor="email">Work email</label>
<input
aria-describedby="email-error"
id="email"
name="email"
required
type="email"
/>
<p id="email-error">{errors.email?.[0]}</p>
<label htmlFor="message">How can we help?</label>
<textarea
aria-describedby="message-error"
id="message"
name="message"
required
/>
<p id="message-error">{errors.message?.[0]}</p>
<p aria-live="polite">
{state.status === "sent" ? "Message sent." : null}
</p>
<button disabled={pending} type="submit">
{pending ? "Sending…" : "Send message"}
</button>
</form>
);
}useActionState adds the client enhancement while preserving the form’s server action. Its pending value makes duplicate submission less likely. For a reusable submit control, useFormStatus can read pending status from the containing form. Keep the smallest possible client boundary: the route, data access, and static surrounding content do not need to become client components merely because a form reports errors.
Choose what happens after success
Success is a state transition, not merely a green message. A create action may redirect to the newly created resource. An inline preference save may retain the form and show confirmation. A support request may reset its message field but preserve the email address. Decide this deliberately before reaching for form.reset().
The action’s data refresh belongs in the same decision. If the next page needs to show a newly created record, invalidate the exact affected path or tagged read model after the mutation commits. Do not refresh an entire layout just to make a local success state appear. A narrow refresh makes both performance and correctness easier to inspect.
For a multi-action form—save draft versus publish, for example—give each submit control a distinct formAction and an explicit result contract. A generic submitted: true value cannot explain whether the document is merely saved, published, or rejected by a workflow rule.
Make Pending and Errors Accessible
An error is part of the form’s meaning, not a red decoration. Tie field-level error text to its input with aria-describedby; use a concise summary or alert when several errors need attention; retain the submitted values where possible so a person can correct rather than re-enter. Announce status changes through a live region, and use a button label that describes the action in both resting and pending states.
Do Not Turn Every Failure Into a Toast
A transient toast is easy to miss and rarely tells a person which field needs work. Put validation feedback beside the affected control; reserve a global message for an outcome that applies to the whole form.
Focus management is a product decision. After a field-validation failure, move focus to an error summary or first invalid field when that helps a keyboard user recover. After a successful navigation, the destination heading is usually the meaningful focus target. Test with a keyboard and screen reader rather than assuming a visual state change is enough.
Preserve intent when the network is unreliable
Pending UI communicates that the browser has attempted a submission, not that the server has committed it. A slow response, refresh, double click, or retry can produce duplicate commands unless the domain has a strategy. For contact forms, a rate limit and an idempotency key may be appropriate. For a payment or booking, the server needs a durable idempotency model and an honest status view rather than a client-side optimistic assumption.
Keep sensitive data out of query strings and avoid logging complete form payloads. Form values frequently contain contact details, secrets, financial data, or private free text. Instrument outcomes—action name, safe correlation ID, validation failure category, duration, and result—without making observability a second copy of customer data.
Unexpected failures deserve an error boundary or controlled global message, not a field error invented from a database exception. The user needs a recovery option such as “Try again” or a support path; the operator needs enough telemetry to investigate. Separating expected input errors from unexpected system failures keeps both paths clear.
Enhance Deliberately, Then Test the Boundary
Optimistic UI is worthwhile when an immediately visible prediction is cheap to correct: starring an item, adding a local draft, or sending a chat message with clear pending treatment. It is a poor default for payments, irreversible deletion, or quota-sensitive inventory. The server remains the source of truth; the interface must recover when the prediction is rejected.
Test the form at the boundaries where it can disappoint a person: browser constraints, server validation, authorization denial, pending duplicate clicks, unexpected errors, and success. Unit-test pure schema or domain code. Integration-test the action with malformed FormData. Render-test error relationships, accessible names, and pending state. End-to-end test the full route, including a no-JavaScript or slow-network path where feasible.
The final question is not “does the button call a function?” It is “can a person understand what this form needs, what it is doing, and what happened afterward?” A native baseline makes that question easier to answer well.
A review checklist for every form
Before a form reaches production, walk its complete path rather than reviewing the JSX in isolation:
- Can a keyboard user identify every field, its required state, and the purpose of submit?
- Does the base form submit to a server-owned action without relying on client state?
- Are server validation, authentication, authorization, and domain rules all applied to the submitted command?
- Are field errors connected to their controls and are whole-form outcomes announced accessibly?
- Does pending UI prevent accidental duplicate work without obscuring what is happening?
- Is success followed by the correct redirect, local confirmation, reset behaviour, and data refresh?
- Can the operation be retried safely, and can operators investigate an unexpected failure without reading sensitive form data?
This checklist also reveals when a form is trying to be an application workflow. A one-step profile edit belongs in a form. A multi-stage onboarding, payment approval, or bulk import may need explicit persisted steps, a resumable job, and an audit trail. Do not force a workflow into one request merely because its first screen has inputs.
Key Takeaways
- Start with semantic HTML forms and a real server action; progressive enhancement builds on that foundation.
- Keep browser constraints for fast feedback, but parse and validate all
FormDataon the server. - Return expected validation failures as a small, UI-safe state protocol.
- Make error, pending, and success states perceivable through labels, relationships, and live feedback.
- Add client state and optimism only when the interaction benefits, then test the failure and recovery paths.
Next, we apply the same boundary thinking to AI systems: least privilege for agents, where tool capabilities stay narrow enough to review, revoke, and compose safely.