API Contracts and Zod Validation
Generate Zod schemas with TypeScript type inference for forms, API routes, and Server Actions. Validate inputs in Server Actions or route handlers with runtime type checking.
Core Capabilities
1. Generate Zod Schemas from TypeScript Types
When creating API contracts or form validations:
- Analyze existing TypeScript interfaces or types
- Generate equivalent Zod schemas with proper validation rules
- Ensure bidirectional type compatibility (Zod -> TypeScript)
- Use
z.infer<typeof schema> for automatic type inference
2. Form Validation Schemas
To create form validation with Zod:
- Generate schemas for React Hook Form, Formik, or native forms
- Include field-level validation rules (min/max length, regex, custom validators)
- Support nested objects, arrays, and complex data structures
- Provide helpful error messages for validation failures
- Use
references/zod_patterns.md for common validation patterns
3. API Route and Server Action Validation
To add validation to API endpoints or Server Actions:
- Wrap handler logic with schema validation using
.parse() or .safeParse()
- Return typed errors for validation failures
- Generate request/response schemas for API contracts
- Validate query parameters, body payloads, and route parameters
- Ensure type safety between client and server code
4. Schema Generation Script
Use scripts/generate_zod_schema.py to automate schema generation:
python scripts/generate_zod_schema.py --input types/entities.ts --output schemas/entities.ts
The script:
- Parses TypeScript interfaces/types
- Generates Zod schemas with appropriate validators
- Preserves JSDoc comments as descriptions
- Handles common patterns (optional fields, unions, enums)
Resource Files
scripts/generate_zod_schema.py
Automated TypeScript-to-Zod schema generator. Parses TypeScript AST and generates equivalent Zod schemas.
references/zod_patterns.md
Common Zod validation patterns including:
- String validation (email, URL, UUID, custom regex)
- Number constraints (min, max, positive, integer)
- Date validation and transformation
- Array and tuple validation
- Object shape validation
- Union and discriminated unions
- Optional and nullable fields
- Custom refinements and transforms
- Error message customization
assets/schema_templates/
Pre-built Zod schema templates:
form_schema_template.ts - Basic form validation
api_route_schema_template.ts - API route request/response
server_action_schema_template.ts - Server Action input/output
entity_schema_template.ts - Database entity validation
Usage Workflow
For New API Routes
- Define request/response TypeScript types
- Generate Zod schemas using
scripts/generate_zod_schema.py or templates
- Add validation middleware to route handler
- Return typed validation errors on failure
For Server Actions
- Define input parameters as TypeScript types
- Create Zod schema for validation
- Use
.safeParse() at the beginning of the action
- Return validation errors in action result
- Handle errors on the client side
For Forms
- Define form fields as TypeScript interface
- Generate Zod schema with field validators
- Integrate with form library (React Hook Form recommended)
- Display validation errors inline
Best Practices
- Always use
.safeParse() instead of .parse() to avoid throwing exceptions
- Provide clear, user-friendly error messages
- Validate early (at API boundary or Server Action entry)
- Keep schemas colocated with routes/actions for maintainability
- Use
z.infer<typeof schema> for automatic TypeScript types
- Document validation rules in schema comments
- Test edge cases (empty values, invalid formats, boundary conditions)
Common Use Cases
Common patterns for applications:
- Entity creation forms: Validate character, location, or data entry forms
- Relationship APIs: Ensure valid entity IDs and relationship types
- Timeline events: Validate dates, ordering, and event data
- Search/filter endpoints: Validate query parameters and filters
- Bulk operations: Validate arrays of entities or updates
- Import/export: Validate file formats and data structure
Consult references/zod_patterns.md for specific validation patterns applicable to your data models.
1---2name: api-contracts-and-zod-validation-23description: Generate Zod schemas and TypeScript types for forms, API routes, and Server Actions with runtime validation. Use this skill when creating API contracts, validating request/response payloads, generating form schemas, adding input validation to Server Actions or route handlers, or ensuring type safety across client-server boundaries. Trigger terms include zod, schema, validation, API contract, form validation, type inference, runtime validation, parse, safeParse, input validation, request validation, Server Action validation.4---56# API Contracts and Zod Validation78Generate Zod schemas with TypeScript type inference for forms, API routes, and Server Actions. Validate inputs in Server Actions or route handlers with runtime type checking.910## Core Capabilities1112### 1. Generate Zod Schemas from TypeScript Types1314When creating API contracts or form validations:1516- Analyze existing TypeScript interfaces or types17- Generate equivalent Zod schemas with proper validation rules18- Ensure bidirectional type compatibility (Zod -> TypeScript)19- Use `z.infer<typeof schema>` for automatic type inference2021### 2. Form Validation Schemas2223To create form validation with Zod:2425- Generate schemas for React Hook Form, Formik, or native forms26- Include field-level validation rules (min/max length, regex, custom validators)27- Support nested objects, arrays, and complex data structures28- Provide helpful error messages for validation failures29- Use `references/zod_patterns.md` for common validation patterns3031### 3. API Route and Server Action Validation3233To add validation to API endpoints or Server Actions:3435- Wrap handler logic with schema validation using `.parse()` or `.safeParse()`36- Return typed errors for validation failures37- Generate request/response schemas for API contracts38- Validate query parameters, body payloads, and route parameters39- Ensure type safety between client and server code4041### 4. Schema Generation Script4243Use `scripts/generate_zod_schema.py` to automate schema generation:4445```bash46python scripts/generate_zod_schema.py --input types/entities.ts --output schemas/entities.ts47```4849The script:50- Parses TypeScript interfaces/types51- Generates Zod schemas with appropriate validators52- Preserves JSDoc comments as descriptions53- Handles common patterns (optional fields, unions, enums)5455## Resource Files5657### scripts/generate_zod_schema.py58Automated TypeScript-to-Zod schema generator. Parses TypeScript AST and generates equivalent Zod schemas.5960### references/zod_patterns.md61Common Zod validation patterns including:62- String validation (email, URL, UUID, custom regex)63- Number constraints (min, max, positive, integer)64- Date validation and transformation65- Array and tuple validation66- Object shape validation67- Union and discriminated unions68- Optional and nullable fields69- Custom refinements and transforms70- Error message customization7172### assets/schema_templates/73Pre-built Zod schema templates:74- `form_schema_template.ts` - Basic form validation75- `api_route_schema_template.ts` - API route request/response76- `server_action_schema_template.ts` - Server Action input/output77- `entity_schema_template.ts` - Database entity validation7879## Usage Workflow8081### For New API Routes82831. Define request/response TypeScript types842. Generate Zod schemas using `scripts/generate_zod_schema.py` or templates853. Add validation middleware to route handler864. Return typed validation errors on failure8788### For Server Actions89901. Define input parameters as TypeScript types912. Create Zod schema for validation923. Use `.safeParse()` at the beginning of the action934. Return validation errors in action result945. Handle errors on the client side9596### For Forms97981. Define form fields as TypeScript interface992. Generate Zod schema with field validators1003. Integrate with form library (React Hook Form recommended)1014. Display validation errors inline102103## Best Practices104105- Always use `.safeParse()` instead of `.parse()` to avoid throwing exceptions106- Provide clear, user-friendly error messages107- Validate early (at API boundary or Server Action entry)108- Keep schemas colocated with routes/actions for maintainability109- Use `z.infer<typeof schema>` for automatic TypeScript types110- Document validation rules in schema comments111- Test edge cases (empty values, invalid formats, boundary conditions)112113## Common Use Cases114115Common patterns for applications:116117- **Entity creation forms**: Validate character, location, or data entry forms118- **Relationship APIs**: Ensure valid entity IDs and relationship types119- **Timeline events**: Validate dates, ordering, and event data120- **Search/filter endpoints**: Validate query parameters and filters121- **Bulk operations**: Validate arrays of entities or updates122- **Import/export**: Validate file formats and data structure123124Consult `references/zod_patterns.md` for specific validation patterns applicable to your data models.