0 day streak
javascript / intermediate
Snippet

Server Action Schema Validation with Zod

Using Zod within Server Actions ensures that data sent from the client is type-safe and validated before any database operations occur. This pattern prevents malicious or malformed data from reaching your backend logic.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
'use server';
import { z } from 'zod';
const schema = z.object({
email: z.string().email(),
});
export async function submitForm(prevState, formData) {
const validatedFields = schema.safeParse({
email: formData.get('email'),
});
if (!validatedFields.success) {
return { errors: validatedFields.error.flatten().fieldErrors };
}
// Process valid data
return { success: true };
}
nextjs
Breakdown
1
const validatedFields = schema.safeParse(...)
Uses Zod to validate the input object without throwing an exception.
2
validatedFields.error.flatten().fieldErrors
Converts complex Zod errors into a simple key-value object for UI display.