0 day streak
javascript / intermediate
Snippet

Server-Side Schema Validation with Zod

Using Zod for schema validation in Server Actions ensures that data is type-safe and valid before it reaches your database. It provides a robust way to handle malformed user input.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { z } from 'zod';
const schema = z.object({
email: z.string().email(),
age: z.number().min(18),
});
export async function createUser(formData: FormData) {
const validatedFields = schema.safeParse({
email: formData.get('email'),
age: Number(formData.get('age')),
});
if (!validatedFields.success) {
return { errors: validatedFields.error.flatten().fieldErrors };
}
// Proceed with DB logic
}
nextjs
Breakdown
1
z.object({...})
Defines the shape and constraints of the expected data.
2
safeParse(...)
Checks the data without throwing an error, returning a result object instead.