What is Zod?
TL;DR
TypeScript-first schema validation library in Frontend Accelerator providing runtime validation with static type inference.
Zod is the TypeScript-first schema validation library used in Frontend Accelerator. It provides runtime validation while automatically inferring static TypeScript types from your schemas. This eliminates the need to define types twice and ensures your validation logic and types stay in sync.
Basic schema example:
import * as z from 'zod';
const userSchema = z.object({
name: z.string().min(2, 'Too short'),
email: z.string().email('Invalid email'),
age: z.number().int().positive().min(18),
role: z.enum(['user', 'admin']),
metadata: z.record(z.string())
});
type User = z.infer<typeof userSchema>;
// TypeScript type automatically inferred!
Validation:
const result = userSchema.safeParse(data);
if (result.success) {
// result.data is fully typed
console.log(result.data.name);
} else {
// result.error contains validation errors
console.log(result.error.issues);
}
Server-side validation:
export async function POST(request: Request) {
const body = await request.json();
const validated = userSchema.parse(body);
// Type-safe and validated data
return createUser(validated);
}
Key features:
- Type inference: Static types derived from schemas
- Composable: Build complex schemas from simple ones
- Error messages: Customizable validation messages
- Transformations: Parse and transform data
- Async validation: Support for async refinements
AI-Friendly: Zod schemas are declarative and explicit. AI tools can generate schemas from TypeScript types, suggest validators based on data patterns, and ensure consistent validation across client and server.