Next Server Actions Zod Validation

Validate Next.js server action input with Zod before any mutation, returning typed field errors for progressive enhancement without JS.

TypescriptNextForm Validation

Code

typescriptsnippet
36 lines
import { z } from 'zod';
import { revalidatePath } from 'next/cache';

const FeedbackSchema = z.object({
  email: z.string().email(),
  rating: z.coerce.number().int().min(1).max(5),
  message: z.string().min(10).max(1000),
});

export type FeedbackState =
  | { status: 'idle' }
  | { status: 'error'; fields: Record<string, string> }
  | { status: 'success'; ticket: string };

export async function submitFeedback(
  _prev: FeedbackState,
  formData: FormData,
): Promise<FeedbackState> {
  const parsed = FeedbackSchema.safeParse({
    email: formData.get('email'),
    rating: formData.get('rating'),
    message: formData.get('message'),
  });

  if (!parsed.success) {
    const fields: Record<string, string> = {};
    for (const issue of parsed.error.issues) {
      fields[issue.path.join('.')] ??= issue.message;
    }
    return { status: 'error', fields };
  }

  const ticket = 'FB-' + Date.now().toString(36);
  revalidatePath('/feedback');
  return { status: 'success', ticket };
}

How it works

Count the function submitFeedback as the entire surface area of Next Server Actions Zod Validation.

Repetition is confined to for (const issue of parsed.error.issues) — the rest of the file is straight-line. Every asynchronous step is awaited, so rejections surface where the call happens. From zod it pulls z, revalidatePath — the imports name exactly which library surface the snippet touches.

The return value is newly constructed — inputs are never handed back.

What to watch for

  • Requires zod and next/cache as packages; the snippet will not run without them.

Putting it to use

The primary signature is export async function submitFeedback( _prev: FeedbackState, formData: FormData, )

submitFeedback is the public entry point; everything else in the file exists to support it.

Core lines

fields[issue.path.join('.')] ??= issue.message;
return { status: 'success', ticket };
return { status: 'error', fields };

Interactive Tools for This Topic

FAQ

Does `submitFeedback` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
What does this need from the package registry?
These are real dependencies: `zod` and `next/cache`. Without them the snippet will not load.