Q40: How do you return structured form validation errors from Server Actions using Zod?
Instead of throwing unhandled exceptions, Server Actions validate inputs using schema libraries like Zod. If validation fails, the action returns structured error objects { errors: ... } consumed cleanly by client components using useActionState.
Zod Validation in Server Action
// actions.js
'use server';
import { z } from 'zod';
const schema = z.object({
email: z.string().email(),
});
export async function submitAction(prevState, formData) {
const result = schema.safeParse({ email: formData.get('email') });
if (!result.success) {
return { errors: result.error.flatten().fieldErrors };
}
return { success: true };
}💡 safeParse checks input data, returning typed field errors if validation fails.
Key Takeaways
- Validate inputs server-side using Zod schemas (
schema.safeParse(data)). - Return structured error objects instead of throwing exceptions.
Knowledge Check
What Zod method validates object data without throwing uncaught runtime exceptions?