Request Validator (Zod)
The Request Validator component provides a standardized way to validate request data (body, query parameters, and route parameters) in Servercn using Zod schemas.
It automatically:
- Validates request body, query, and params using Zod schemas
- Returns detailed validation error messages
- Integrates seamlessly with Servercn error handling
- Provides type-safe request data after validation
This middleware is designed for type-safe, schema-based validation in REST APIs.
Installation Guide
npx servercn-cli add request-validatorHow Validation Works
The Request Validator middleware follows this sequence:
- Schema Definition: Define Zod schemas for body, query, or params
- Middleware Application: Apply
validateRequestmiddleware to routes - Validation: Middleware validates incoming request data against schemas
- Error Handling: If validation fails, returns detailed error messages
- Type Safety: Validated data is typed and attached to the request object
This ensures type-safe request handling with clear validation error messages.
Middleware Implementation
MVC: src/middlewares/validate-request.ts
Feature: src/shared/middlewares/validate-request.ts
Schema Definition
Create validation schemas using Zod.
MVC: src/validations/user.validation.ts
Feature: src/modules/user/user.validation.ts
Usage Example
Apply the validateRequest middleware to your routes with the appropriate schema.
src/routes/user.routes.ts
Validation Error Responses
When validation fails, the handler returns a standardized 400 Bad Request response with detailed error information:
(The exact structure depends on your ApiError implementation.)
Best Practices
- Separate Schemas: Create separate validation files for each resource/module
- Reusable Schemas: Extract common validation patterns into shared schemas
- Clear Error Messages: Provide descriptive error messages in your Zod schemas
- Type Safety: Use Zod's type inference for TypeScript type safety
- Transform Data: Use Zod's transform methods to convert query strings to numbers, dates, etc.
- Validate Early: Apply validation middleware before business logic
- Consistent Structure: Keep validation schemas organized and consistent across your application