API Reference
Zod Server Validation
Server-side schema validation with Zod for API request bodies, query params, and environment variables.
Official Documentation ↗CompatibilityThis documentation covers version
v3.23. Check the official docs for the latest API surface.Installation
npm
npm install zodpnpm
pnpm add zodMethods
No methods match this filter.
Zod server-side validation uses the same Zod schemas as the client to validate API requests, environment variables, and configuration. This ensures end-to-end type safety and eliminates the gap between client and server validation logic.
Key Features
- Shared schemas: One schema definition for client and server
- Fail-fast: Environment validation crashes at startup, not at runtime
- Type coercion: Convert string query params to numbers/booleans/dates
- Error formatting: Structured error issues for 400/422 API responses
- Middleware integration: Works with Express, Fastify, Hono, and FastAPI
- OpenAPI generation: Generate API docs from Zod schemas via zod-openapi
FAQ
- Why validate on the server when the client already validates?
- Client validation can be bypassed (curl, Postman, direct API calls). Server-side validation is the source of truth for data integrity. Using the same Zod schema on both client and server ensures consistency and eliminates drift.
- How do I format ZodError for API responses?
- Map result.error.issues to { field: path.join('.'), message } objects. Or use zod-to-openapi to generate OpenAPI error schemas. Always return 422 or 400 with structured error details.
- Can I reuse schemas between client and server?
- Yes. Define schemas in a shared package (monorepo) or shared directory. Import the same schema in React Hook Form (client) and Express middleware (server). This guarantees end-to-end type safety.
Report a problem with this API docOpens a pre-filled issue on GitHub.