Next.js Server-Side Form Validation

Validate forms in Next.js App Router using server actions with Zod schema validation. Returns typed error objects to the client component and prevents.

TypescriptNextForm Validation

Code

snippet
import { z } from 'zod';

const schema = z.object({
  email: z.string().email('Invalid email'),
  password: z.string().min(8, 'Min 8 characters'),
});

export async function loginAction(formData: FormData) {
  const parsed = schema.safeParse({
    email: formData.get('email'),
    password: formData.get('password'),
  });
  if (!parsed.success) {
    return { errors: parsed.error.flatten().fieldErrors };
  }
  const user = await authenticate(parsed.data);
  return { user };
}

How the snippet works

Count the function loginAction as the entire surface area of Next.js Server-Side Form Validation.

The asynchronous flow is linearized with await, keeping failure handling local. z are the only symbols borrowed from zod — the coupling is explicit and narrow.

Returns a newly built value, leaving the inputs as they were.

What to watch for

  • Plan for an install step: zod is a real dependency, resolved by the package manager.
  • The guard !parsed.success short-circuits the flow with an early return when its condition holds.

Applying it

The main signature reads export async function loginAction(formData: FormData)

loginAction is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

return { errors: parsed.error.flatten().fieldErrors };
const user = await authenticate(parsed.data);
return { user };

Interactive Tools for This Topic

FAQ

Does `loginAction` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
Which packages must be installed first?
Yes. The imports resolve to `zod`, which the package manager must provide.