zod

TypeScript-first schema validation and type inference. Use for validating API requests/responses, form data, env vars, configs, defining type-safe schemas with runtime validation, transforming data, generating JSON Schema for OpenAPI/AI, or encountering missing validation errors, type inference issu

By secondsky · 582 installs

npx skills add secondsky/claude-skills --skill zod

Source repository · Upstream listing

Zod: TypeScript First Schema Validation Overview Zod is a TypeScript first validation library that enables developers to define schemas for validating data at runtime while automatically inferring static TypeScript types. With zero dependencies and a compact core (~5kb gzipped; ~1.9kb for zod/mini ), Zod provides immutable, composable validation with comprehensive error handling. Installation Requirements : TypeScript v5.5+ with "strict": true in tsconfig.json Zod 4.x (4.4.x recommended; z.codec() requires 4.1+) Important : This skill documents Zod 4.x features. The following APIs require Zod 4 and are NOT available in Zod 3.x: z.codec() Bidirectional transformations z.iso.date() , z.iso.time() , z.iso.datetime() , z.iso.duration() ISO format validators z.toJSONSchema() JSON Schema generation z.treeifyError() , z.prettifyError() , z.flattenError() New error formatting helpers .meta() Enhanced metadata (Zod 3.x only has .describe() ) Unified error parameter Replaces message , invalid type error , required error , errorMap .check() Low level multi issue validation (composes check factories like z.minLength(3) ) z.file() , z.json() , z.stringbool() , z.xor() , z.templateLiteral() New schema types z.exactOptional() , .prefault() , .safeExtend() , z.fromJSONSchema() New utilities For Zod 3.x compatibility or migration guidance, see https://zod.dev Import paths (all ship in the zod package): import { z } from "zod" — standard (v4 since 4.0) import { z } from "zod/v4" — pin for libraries supporting both v3 (3.25+) and v4 users import { z } from "zod/mini" — functional, tree shakable API (~1.9kb; checks via .check(z.minLength(3)) ) import as core from "zod/v4/core" — low level $ prefixed internals for library authors Migrating from Zod v3 to v4 Load references/migration guide.md for complete v3 to v4 migration documentation. Quick Summary Zod v4 introduces breaking changes for better performance: Error customization : Use unified error parameter (replaces message , invalid type error , required error ) Number validation : Stricter rejects Infinity and unsafe integers String formats : Prefer top level functions ( z.email() instead of z.string().email() ; the method forms still work but are deprecated) Object defaults : Applied even in optional fields Deprecated APIs : Use .extend() (not .merge() ), z.treeifyError() (not error.format() ) Function validation : Use .implement() method UUID validation : Stricter RFC 9562/4122 compliance → Load references/migration guide.md for: Complete breaking changes, migration checklist, gradual migration strategy, rollback instructions Core Concepts Basic Usage Pattern Parsing Methods Use the appropriate parsing method based on error handling needs: .parse(data) Throws ZodError on invalid input; returns strongly typed data on success .safeParse(data) Returns { success: true, data } or { success: false, error } (no exceptions) .parseAsync(data) For schemas with async refinements/transforms .safeParseAsync(data) Async version that doesn't throw Best Practice : Use .safeParse() to avoid try catch blocks and leverage discriminated unions. Primitive Types Strings Numbers Coercion (Type Conversion) Other Primitives Complex Types Objects Arrays Tuples Enums and Literals Unions Intersections Records and Maps Advanced Patterns Load references/advanced patterns.md for complete advanced validation and transformation patterns. Quick Reference Refinements (custom validation): Transformations (modify data): Multi issue validation ( .check() , v4): Template literals (v4): Codecs (bidirectional transforms NEW in v4.1): Recursive Types : Optional/Nullable : Readonly & Brand : → Load references/advanced patterns.md for: Complete refinement patterns, async validation, codec examples, composable schemas, conditional validation, performance optimization Error Handling Load references/error handling.md for complete error formatting and customization guide. Quick Reference Error Formatting Methods : Custom Error Messages (three levels): Localization (40+ languages): → Load references/error handling.md for: Complete error formatting examples, custom error patterns, localization setup, error code reference Type Inference Load references/type inference.md for complete type inference and metadata documentation. Quick Reference Basic Type Inference : Input vs Output (for transforms): JSON Schema Conversion : Metadata : → Load references/type inference.md for: Complete type inference patterns, JSON Schema options, metadata system, custom registries, brand types Functions Validate function inputs and outputs with the v4 factory signature: Note : the v3 chaining style ( z.function().args(...).returns(...) ) was removed in v4. Common Patterns Environment Variables API Request Validation Form Validation Partial Updates Composable Schemas Ecosystem Integration Load references/ecosystem integrations.md for complete framework and tooling integration guide. Quick Reference ESLint Plugins : eslint plugin zod x Enforces best practices eslint plugin import zod Enforces import style Framework Integrations : tRPC End to end typesafe APIs React Hook Form Form validation (see react hook form zod skill) Prisma Generate Zod from database models NestJS DTOs and validation pipes Code Generation : orval OpenAPI → Zod Hey API OpenAPI to TypeScript + Zod kubb API toolkit with codegen → Load references/ecosystem integrations.md for: Setup instructions, integration examples, Hono middleware, Drizzle ORM patterns Troubleshooting Load references/troubleshooting.md for complete troubleshooting guide, performance tips, and best practices. Quick Reference Common Issues : 1. TypeScript strict mode required → Enable in tsconfig.json 2. Large bundle size → Use z.lazy() for code splitting 3. Slow async refinements → Cache or debounce 4. Circular dependencies → Use z.lazy() 5. Slow unions → Use z.discriminatedUnion() 6. Transform vs refine confusion → Use .refine() for validation, .transform() for modification Performance Tips : Use .discriminatedUnion() (5 10x faster than .union() ) Cache schema instances Use .safeParse() (avoids try catch overhead) Lazy load large schemas Best Practices : Define schemas at module level Use type inference ( z.infer ) Add custom error messages Validate at system boundaries Compose small schemas Document with .meta() → Load references/troubleshooting.md for: Detailed solutions, performance optimization, best practices, testing patterns Quick Reference When to Load References Load references/migration guide.md when: Upgrading from Zod v3 to v4 Questions about breaking changes Need migration checklist or rollback strategy Errors related to deprecated APIs ( .merge() , error.format() , etc.) Number validation issues with Infinity or unsafe integers Load references/error handling.md when: Need to format errors for forms or UI Implementing custom error messages Questions about z.flattenError() , z.treeifyError() , or z.prettifyError() Setting up localization for error messages Need error code reference or pattern examples Load references/advanced patterns.md when: Implementing custom refinements or async validation Need bidirectional transformations (codecs) Working with recursive types or self referential data Questions about .refine() , .transform() , or .codec() Need performance optimization patterns Implementing conditional validation Load references/type inference.md when: Questions about TypeScript type inference Need to generate JSON Schema for OpenAPI or AI Implementing metadata system for forms or documentation Need custom registries for type safe metadata Questions about z.infer , z.input , z.output Using brand types for ID safety Load references/ecosystem integrations.md when: Integrating with tRPC, React Hook Form, Prisma, or NestJS Setting up ESLint plugins for best practices Generating Zod schemas from OpenAPI (orval, Hey API, kubb) Questions about Hono middleware or Drizzle ORM Need framework specific integration examples Load references/troubleshooting.md when: Encountering TypeScript strict mode errors Bundle size concerns or lazy loading needs Performance issues with large unions or async refinements Questions about circular dependencies Need best practices or testing patterns Confusion between .refine() and .transform() Load references/best practices.md when: Writing production Zod code or reviewing Zod usage Deciding strict vs loose objects, optional vs nullable, any vs unknown Optimizing hot paths (schema caching, avoiding dynamic schema creation, large arrays) Unsure where to validate (boundaries, JSON.parse , double validation) Want Incorrect/Correct examples with "when NOT to use" guidance Additional Resources Official Docs : https://zod.dev GitHub : https://github.com/colinhacks/zod TypeScript Playground : https://zod playground.vercel.app Zod Mini : https://zod.dev/packages/mini ESLint Plugin (Best Practices) : https://github.com/JoshuaKGoldberg/eslint plugin zod x tRPC Integration : https://trpc.io Ecosystem : https://zod.dev/ecosystem Production Notes : Package version: 4.4.x (all APIs verified against zod@4.4.3) Zero dependencies Bundle size: ~5kb core / ~1.9kb zod/mini (gzipped) TypeScript 5.5+ required Strict mode required Last verified: 2026 08 20 Skill version: 2.1.0 (fidelity audit + best practices rules) What's New in 2.1.0 : 🔍 Fidelity audit: every documented API verified against zod@4.4.3 (typecheck + runtime tests) 📜 New references/best practices.md rulebook (Incorrect/Correct/When NOT format with impact ratings) ➕ New coverage: zod/mini , .check() , catchall , z.preprocess , z.custom , z.templateLiteral , z.file / z.json / z.stringbool / z.xor , z.exactOptional , .safeExtend , z.fromJSONSchema , expanded format validators 🐛 Fixed: install commands, z.string().uuid() → z.uuid() , v3 .merge() / z.function() chains, .deepPartial() (removed in v4), single arg z.record , toJSONSchema metadata option What's New in 2.0.0 : ✨ Comprehensive v3 to v4 migration guide with breaking changes ✨ Enhanced error customization with three level system ✨ Expanded metadata API with registry system ✨ Improved error formatting with practical examples ✨ Built in localization support for 40+ locales ✨ Detailed codec documentation with real world patterns ✨ Performance improvements and architectural changes explained