Tip
zod-codepen is a powerful library that converts live Zod schema objects into equivalent TypeScript/JavaScript code strings. Perfect for debugging, code generation, schema visualization, and building developer tools.
- Dual Version Support - Works with both Zod v3 and Zod v4 (including all v4 variants)
- 40+ Schema Types - Comprehensive coverage of primitives, composites, modifiers, and effects
- Code Optimizations - Semantic methods (
.positive()) and scientific notation (2**31 - 1) - Formatted Output - Pretty-printed code with customizable indentation
- Module Generation - Generate complete TypeScript/JavaScript modules with exports
- Extensible - Register custom handlers for special schema types
- Zero Runtime Overhead - Tree-shakeable ESM modules
Choose the package matching your Zod version:
# For Zod v3 npm install @zod-codepen/zod-v3 # For Zod v4 npm install @zod-codepen/zod-v4import { serialize } from "@zod-codepen/zod-v3"; // or @zod-codepen/zod-v4 import { z } from "zod"; // Basic serialization serialize(z.string()); // → 'z.string()' // With constraints serialize(z.string().email().min(5).max(100)); // → 'z.string().email().min(5).max(100)' // Complex objects const UserSchema = z.object({ id: z.string().uuid(), email: z.string().email(), age: z.number().int().min(0).optional(), role: z.enum(["admin", "user", "guest"]), }); serialize(UserSchema); // → z.object({ // id: z.string().uuid(), // email: z.string().email(), // age: z.number().int().nonnegative().optional(), // role: z.enum(["admin", "user", "guest"]) // }) // Code optimizations (enabled by default) serialize(z.number().min(0)); // → 'z.number().nonnegative()' serialize(z.number().max(2147483647)); // → 'z.number().max(2**31 - 1)'Serialize a single Zod schema to a code string.
serialize(schema: unknown, options?: SerializeOptions): stringOptions:
indent- Indentation string (default:' ')format- Enable pretty-printing (default:true)indentLevel- Starting indentation level (default:0)
Generate a complete TypeScript module with named schema exports.
import { generateModule } from "@zod-codepen/zod-v3"; const schemas = { User: z.object({ id: z.number(), name: z.string() }), Status: z.enum(["active", "inactive"]), }; generateModule(schemas); // → import { z } from 'zod'; // // export const User = z.object({ // id: z.number(), // name: z.string() // }); // // export const Status = z.enum(["active", "inactive"]);Register a custom handler for a schema type.
import { registerHandler } from "@zod-codepen/zod-v3"; registerHandler("custom", (schema, ctx) => { return "z.custom(/* ... */)"; });| Category | Types |
|---|---|
| Primitives | string, number, boolean, bigint, date, undefined, null, void, any, unknown, never, nan, symbol |
| Literals & Enums | literal, enum, nativeEnum |
| Wrappers | optional, nullable, nullish, default, catch, readonly, branded |
| Collections | array, object, record, map, set, tuple |
| Union Types | union, discriminatedUnion, intersection |
| Advanced | lazy, promise, function, effects, pipe/pipeline |
// String constraints z.string() .min(1) .max(100) .email() .url() .uuid() .regex(/pattern/); // Number constraints z.number().min(0).max(100).int().positive().negative().finite(); // Array constraints z.array(z.string()).min(1).max(10).nonempty(); // Object modifiers z.object({}).strict().passthrough().partial().required();The library handles internal structure differences between Zod versions automatically:
| Feature | v3 | v4 |
|---|---|---|
| Type detection | _def.typeName | _zod.def.type |
| Constraint format | checks: [{kind}] | checks: [{_zod: {def}}] |
| All v4 variants | - | zod, zod/mini, zod/v4, zod/v4/core |
Both adapters produce identical output format, making migration seamless.
zod-codepen/ ├── pkgs/ │ ├── core/ # Core serialization engine (version-agnostic) │ ├── zod-v3/ # Zod v3 adapter │ └── zod-v4/ # Zod v4 adapter └── docs/ # VitePress documentation - Schema Visualization - Display Zod schemas in developer tools
- Code Generation - Generate schema files from runtime definitions
- Debugging - Inspect complex schema structures
- Documentation - Auto-generate API documentation
- Migration Tools - Compare schemas across versions
- Testing - Snapshot testing for schema definitions
Visit the documentation site for detailed guides and API reference.
# Install dependencies pnpm install # Build all packages pnpm build # Run tests pnpm test # Run v3/v4 tests separately pnpm test:v3 pnpm test:v4 # Start documentation dev server pnpm docs:devContributions are welcome! Please read our Contributing Guide for details.
- Fork the repository
- Create your feature branch (
git checkout -b feat/amazing-feature) - Commit your changes (
git commit -m 'feat: add amazing feature') - Push to the branch (
git push origin feat/amazing-feature) - Open a Pull Request
MPL2.0 | Mozilla Public License 2.0 - Created by CornWorld
Announce: This project is not affiliated with CodePen.io. The codepen in the name is just a coincidence, representing the function of this project is to serialize zod schema to code string as easy as a pen.