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 issues, validation error handling problems. Zero dependencies, compact core (~5kb gzipped; zod/mini ~1.9kb).
- Skill ID
- secondsky/claude-skills/zod
- Publisher
- secondsky
- Repository
- claude-skills
- Installs
- 0
- Files
- 13
- License
- MIT
- Synced
- Sep 23, 2026
Open any RiverX project, open the Skills panel in the chat, and search for this identifier. The files are fetched from the source repository at install time.
secondsky/claude-skills/zodInstalls these files- SKILL.md
- references/advanced-patterns.md
- references/best-practices.md
- references/common-patterns.ts
- references/ecosystem-integrations.md
- references/error-handling.md
- references/eslint.config.js
- references/migration-guide.md
- references/package.json
- references/quick-reference.md
- references/troubleshooting.md
- references/tsconfig.json
- references/type-inference.md
What this skill tells the agent
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
bun add zod
# or
npm install zod
# or
pnpm add zod
# or
yarn add zodRequirements:
- TypeScript v5.5+ with
"strict": trueintsconfig.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 transformationsz.iso.date(),z.iso.time(),z.iso.datetime(),z.iso.duration()- ISO format validatorsz.toJSONSchema()- JSON Schema generationz.treeifyError(),z.prettifyError(),z.flattenError()- New error formatting helpers.meta()- Enhanced metadata (Zod 3.x only has.describe())- Unified
errorparameter - Replacesmessage,invalid_type_error,required_error,errorMap .check()- Low-level multi-issue validation (composes check factories likez.minLength(3))z.file(),z.json(),z.stringbool(),z.xor(),z.templateLiteral()- New schema typesz.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 usersimport { 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
errorparameter (replacesmessage,invalid_type_error,required_error) - Number validation: Stricter - rejects
Infinityand unsafe integers - String formats: Prefer top-level functions (
z.email()instead ofz.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()(noterror.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
import { z } from "zod";
// Define schema
const UserSchema = z.object({
username: z.string(),
age: z.number().int().positive(),
email: z.email(),
});
// Infer TypeScript type
type User = z.infer<typeof UserSchema>;
// Validate data (throws on error)
const user = UserSchema.parse(data);
// Validate data (returns result object)
const result = UserSchema.safeParse(data);
if (result.success) {
console.log(result.data); // Typed!
} else {
console.error(result.error); // ZodError
}Parsing Methods
Use the appropriate parsing method based on error handling needs:
- `.parse(data)` - Throws
ZodErroron 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
z.string() // Basic string
z.string().min(5) // Minimum length
z.string().max(100) // Maximum length
z.string().length(10) // Exact length
z.email() // Email validation (top-level in v4)
z.url() // URL validation (top-level in v4)
z.uuid() // UUID (RFC 9562; use z.guid() for permissive)
z.uuidv4() // Version-specific UUIDs (also z.uuidv7)
z.httpUrl() // http/https URLs only (rejects ftp:// etc.)
z.e164() // Phone numbers (E.164 format)
z.string().regex(/^\d+$/) // Custom pattern
z.string().startsWith("pre") // Prefix check
z.string().endsWith("suf") // Suffix check
z.string().trim() // Auto-trim whitespace
z.string().toLowerCase() // Auto-lowercase
z.string().toUpperCase() // Auto-uppercase
// ISO formats (Zod 4+)
z.iso.date() // YYYY-MM-DD
z.iso.time() // HH:MM:SS
z.iso.datetime() // ISO 8601 datetime
z.iso.duration() // ISO 8601 duration
// Network formats
z.ipv4() // IPv4 address
z.ipv6() // IPv6 address
z.cidrv4() // IPv4 CIDR notation
z.cidrv6() // IPv6 CIDR notation
// Other formats
z.jwt() // JWT token
z.nanoid() // Nanoid
z.cuid() // CUID
z.cuid2() // CUID2
z.ulid() // ULID
z.base64() // Base64 encoded
z.hex() // Hexadecimal
z.hash("sha256") // Hash of algorithm-specific length
z.guid() // Permissive UUID/GUID (non-RFC)
z.hostname() // Hostname
z.mac() // MAC address
z.uuid({ version: "v4" }) // UUID with version constraint
z.email({ pattern: z.regexes.email }) // Email with explicit patternNumbers
z.number() // Basic number
z.number().int() // Integer only
z.number().positive() // > 0
z.number().nonnegative() // >= 0
z.number().negative() // < 0
z.number().nonpositive() // <= 0
z.number().min(0) // Minimum value
z.number().max(100) // Maximum value
z.number().gt(0) // Greater than
z.number().gte(0) // Greater than or equal
z.number().lt(100) // Less than
z.number().lte(100) // Less than or equal
z.number().multipleOf(5) // Must be multiple of 5
z.int() // Shorthand for z.number().int()
z.int32() // 32-bit integer (also z.uint32, z.int64, z.uint64)
z.float32() // 32-bit float (also z.float64)
z.nan() // NaN valueCoercion (Type Conversion)
z.coerce.string() // Convert to string
z.coerce.number() // Convert to number
z.coerce.boolean() // Convert to boolean
z.coerce.bigint() // Convert to bigint
z.coerce.date() // Convert to Date
// Example: Parse query parameters
const QuerySchema = z.object({
page: z.coerce.number().int().positive(),
limit: z.coerce.number().int().max(100).default(10),
});
// "?page=5&limit=20" -> { page: 5, limit: 20 }Other Primitives
z.boolean() // Boolean
z.date() // Date object
z.date().min(new Date("2020-01-01"))
z.date().max(new Date("2030-12-31"))
z.bigint() // BigInt
z.symbol() // Symbol
z.null() // Null
z.undefined() // Undefined
z.void() // Void (undefined)
// File validation (v4) — sizes are bytes
z.file().min(1).max(5 * 1024 * 1024).mime(["image/png"])
// JSON-representable values (v4) — validates the VALUE is JSON-serializableMore from secondsky
Use this skill in a project
Open any RiverX project, search the Skills panel for secondsky/claude-skills/zod, and install it in one click.
