Home · About · Services · Industries · Projects · Products · Process · Blog · Glossary · FAQ · Contact
Next.js Server Actions for forms: validation and security A worked Next.js Server Actions pattern for forms: Zod validation, field errors with useActionState, revalidation and the authorisation checks teams forget.
A team moves its admin panel to the Next.js App Router. Forms that used to post to API routes now call Server Actions. The code is shorter and the demo works. A month later, a code review finds that the “delete customer” action checks nothing. Any logged-in user who knows a customer ID can call it. The button was merely hidden in the UI.
A Server Action is a public HTTP endpoint with a nice calling syntax. Treat it exactly like an API route. Validate every input on the server and check authentication and authorisation inside the action itself. Return structured errors for the form, and revalidate the data you changed. Done that way, Server Actions remove a lot of boilerplate without removing any safety.
What a Server Action really is A function marked with the "use server" directive runs only on the server. When a form’s action prop points at it, Next.js sends a POST request with the form data. The request goes to the current route, identified by an action ID. React handles the pending state and the response.
Because it is a POST endpoint, anyone can call it with crafted data, not only your form. Hidden fields can be changed, disabled buttons can be bypassed, and client-side validation can be skipped. Next.js 15 makes action IDs harder to guess and removes unused actions from the build, which helps. It does not replace checks in your own code.
The pattern: one action, four steps Every mutating action should follow the same order: authenticate, validate, authorise, then mutate and revalidate. Here is a complete example for editing a customer record.
// app/customers/[id]/edit/actions.ts
'use server';
import { z } from 'zod';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { getSession } from '@/lib/auth';
import { db } from '@/lib/db';
const CustomerSchema = z.object({
id: z.string().uuid(),
name: z.string().trim().min(2, 'Name is too short').max(120),
email: z.string().trim().email('Enter a valid email'),
gstin: z
.string()
.trim()
.regex(/^[0-9]{2}[A-Z0-9]{13}$/, 'GSTIN must be 15 characters')
.optional()
.or(z.literal('')),
});
export type FormState = {
ok: boolean;
message?: string;
errors?: Partial<Record<'name' | 'email' | 'gstin', string[]>>;
};
export async function updateCustomer(
_prev: FormState,
formData: FormData,
): Promise<FormState> {
// 1. Authenticate
const session = await getSession();
if (!session) return { ok: false, message: 'Please sign in again.' };
// 2. Validate
const parsed = CustomerSchema.safeParse(Object.fromEntries(formData));
if (!parsed.success) {
return { ok: false, errors: parsed.error.flatten().fieldErrors };
}
const input = parsed.data;
// 3. Authorise against the actual record, not the form
const customer = await db.customer.findUnique({ where: { id: input.id } });
if (!customer || customer.orgId !== session.orgId || !session.can('customer:edit')) {
return { ok: false, message: 'You do not have access to this customer.' };
}
// 4. Mutate and revalidate
await db.customer.update({
where: { id: input.id },
data: { name: input.name, email: input.email, gstin: input.gstin || null },
});
revalidatePath(`/customers/${input.id}`);
revalidatePath('/customers');
redirect(`/customers/${input.id}`);
}Note the authorisation step loads the customer from the database and checks its organisation. Trusting an orgId sent in the form would let a user edit another tenant’s data by changing a hidden field.
Showing errors and pending state React 19 provides useActionState, which replaces the earlier useFormState from react-dom. It wires the action’s return value back into the component. useFormStatus gives a submit button access to the pending state of its parent form.
// app/customers/[id]/edit/form.tsx
'use client';
import { useActionState } from 'react';
import { useFormStatus } from 'react-dom';
import { updateCustomer, type FormState } from './actions';
function SubmitButton() {
const { pending } = useFormStatus();
return <button type="submit" disabled={pending}>{pending ? 'Saving…' : 'Save'}</button>;
}
export function CustomerForm({ customer }: { customer: { id: string; name: string; email: string; gstin: string | null } }) {
const [state, formAction] = useActionState<FormState, FormData>(updateCustomer, { ok: true });
return (
<form action={formAction} noValidate>
<input type="hidden" name="id" value={customer.id} />
<label htmlFor="name">Name</label>
<input id="name" name="name" defaultValue={customer.name}
aria-invalid={!!state.errors?.name} aria-describedby="name-error" />
<p id="name-error" role="alert">{state.errors?.name?.[0]}</p>
<label htmlFor="email">Email</label>
<input id="email" name="email" type="email" defaultValue={customer.email}
aria-invalid={!!state.errors?.email} aria-describedby="email-error" />
<p id="email-error" role="alert">{state.errors?.email?.[0]}</p>
{state.message && <p role="alert">{state.message}</p>}
<SubmitButton />
</form>
);
}Because the form posts natively, it works before JavaScript loads. That is progressive enhancement for free. One caution: in React 19, a form action resets uncontrolled fields after submission. If validation fails, return the submitted values in the state and use them as default values, or users lose what they typed.
Validation belongs on the server Client-side validation improves the experience, but only server-side validation protects the data. Define one Zod schema and use it in both places if you like, but always parse on the server inside the action.
Use safeParse, not parse, so validation failures become form errors rather than thrown exceptions. Trim and normalise strings in the schema, so stored data is consistent. Coerce numbers and dates explicitly with z.coerce, since FormData values are always strings or files. Limit string lengths and file sizes. The default body size limit for Server Actions is 1 MB, configurable through experimental.serverActions.bodySizeLimit in next.config. Never pass the whole parsed object straight to the database. Pick the fields a user is allowed to change. Keep schemas next to the actions that use them, or in a shared module when several forms edit the same entity. When the database gains a new column, the schema is the one place to update. TypeScript will then flag every action that needs the field.
Revalidation and redirects After a mutation, cached pages that show the changed data must be refreshed. revalidatePath clears the cache for a route. revalidateTag clears all fetches tagged with a given name, which is better when the same data appears on many routes.
redirect throws internally to stop execution, so call it outside any try and catch block. If you wrap the database update in try and catch, redirect after the block. Otherwise the catch swallows the redirect and the user stays on the form.
Security checks teams forget Authorisation inside every action, not in the page or layout. Middleware and layouts do not protect actions on their own. Tenant scoping on every query, using the session’s organisation, never a value from the form. Rate limiting for actions that send email, create records or check passwords. Closures over server data: values captured in an inline action are encrypted by Next.js, but secrets should still never be passed through them. Returning raw errors: database messages can leak table names. Log details on the server and return a plain message. Allowed origins: Next.js compares the Origin header with the host to stop cross-site requests. If you sit behind a proxy with a different host, configure experimental.serverActions.allowedOrigins rather than disabling the check. Testing Server Actions Because a Server Action is an ordinary async function, much of it can be tested without a browser. Keep the validation and authorisation logic in plain functions that the action calls, and unit-test those directly with Vitest or Jest.
Unit tests: call the action with a constructed FormData and a mocked session, and assert on the returned state for valid input, invalid input and a user from another organisation. Authorisation tests: for every action, include one test where the user lacks permission and one where the record belongs to another tenant. These are the tests that catch the bug in the opening example. End-to-end tests: use Playwright to submit the real form, check that field errors appear next to the right inputs, and confirm the page shows updated data after a successful save. Replay tests: send a crafted POST that changes a hidden field, and confirm the action refuses it. Mock redirect and revalidatePath in unit tests, or isolate them behind a small wrapper, since they depend on the Next.js request context. Test them properly in the end-to-end suite instead.
A failing authorisation test is the cheapest security finding you will ever get. Make it a rule that no action merges without one.
A review checklist for every action The file or function has "use server" and runs no client code. Session is checked first, and an unauthenticated call returns early. Input is parsed with a schema; failures return field errors. The target record is loaded and checked for ownership and permission. Only permitted fields are written. The right paths or tags are revalidated. redirect is called outside try and catch. Errors shown to users contain no internal details. Put this checklist in your pull request template. Server Actions are easy to write, which means many will be written. A consistent pattern keeps every one of them as safe as the first.
Infigini IT Services · GSTIN 05AAIFI1118B1Z3 · 11 Shree Ram Puram Lane No.2, Kanwali Road, Dehradun, Uttarakhand 248001, India · info@infigini.com · +91 95684 87789 · LinkedIn