Validation with Zod
MoroJS uses Zod for runtime validation and TypeScript type inference. Learn how to validate requests, responses, and create type-safe APIs.
Why Zod?
Zod is a TypeScript-first schema validation library that provides:
- Runtime validation with compile-time type inference
- Zero dependencies and excellent TypeScript support
- Composable and reusable schemas
- Clear error messages and validation feedback
Basic Validation
Request Body Validation
typescript
Parameter Validation
typescript
Query Parameter Validation
typescript
Advanced Schema Patterns
Nested Objects and Arrays
typescript
Conditional Validation
typescript
Custom Validation
typescript
Error Handling
MoroJS automatically handles validation errors and returns structured error responses:
Automatic Error Responses
json
Custom Error Handling
typescript
Schema Composition and Reuse
Reusable Base Schemas
typescript
Schema Transformations
typescript
Best Practices
Do
- • Use descriptive error messages
- • Create reusable base schemas
- • Validate all external inputs
- • Use transformations for data cleaning
- • Define response schemas for documentation
- • Use z.infer for type extraction
Don't
- • Skip validation for "trusted" inputs
- • Use overly complex nested schemas
- • Ignore validation error details
- • Validate the same data multiple times
- • Use any types instead of proper schemas
- • Forget to handle edge cases