npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

prisma2zod

v1.0.1

Published

A TypeScript library that converts Prisma schema to Zod definitions

Readme

Prisma2Zod

A TypeScript library that converts Prisma schema definitions to Zod validation schemas.

Features

  • Convert Prisma models to Zod schemas
  • Support for all Prisma field types
  • Handle optional and required fields
  • Support for enums
  • Generate TypeScript types from Zod schemas
  • Comprehensive error handling
  • CLI tool for easy conversion
  • Custom type mappings support

Installation

npm install prisma2zod

Quick Start

Basic Usage

import { convertPrismaToZod } from 'prisma2zod';

const prismaSchema = `
model User {
  id        Int      @id @default(autoincrement())
  email     String   @unique
  name      String?
  createdAt DateTime @default(now())
}

enum Role {
  USER
  ADMIN
  MODERATOR
}
`;

const result = convertPrismaToZod(prismaSchema);
console.log(result.schemas.User);
// Output:
// export const UserSchema = z.object({
//   id: z.number(),
//   email: z.string(),
//   name: z.string().nullable(),
//   createdAt: z.date(),
// });

CLI Usage

# Convert a Prisma schema file to Zod schemas
npx prisma2zod schema.prisma -o schemas.ts

# Generate separate files for enums and schemas
npx prisma2zod schema.prisma -f separate -o ./generated/

# Include relations and default values
npx prisma2zod schema.prisma --relations --defaults

API Reference

convertPrismaToZod(schema: string, options?: ConvertOptions): ConvertResult

Converts a Prisma schema string to Zod schemas.

Parameters

  • schema (string): The Prisma schema as a string
  • options (ConvertOptions, optional): Configuration options

Returns

  • ConvertResult: Object containing generated schemas and metadata

ConvertOptions

interface ConvertOptions {
  generateTypes?: boolean; // Generate TypeScript types (default: true)
  includeRelations?: boolean; // Include relation fields (default: false)
  customMappings?: Record<string, string>; // Custom type mappings
  includeDefaults?: boolean; // Include default values (default: false)
  includeUniques?: boolean; // Include unique constraints (default: false)
}

ConvertResult

interface ConvertResult {
  schemas: Record<string, string>; // Generated Zod schemas
  types: Record<string, string>; // Generated TypeScript types
  enums: Record<string, string>; // Generated enum schemas
  metadata: {
    models: string[];
    enums: string[];
    errors: string[];
  };
}

Supported Prisma Types

| Prisma Type | Zod Schema | |-------------|------------| | String | z.string() | | Int | z.number() | | Float | z.number() | | Boolean | z.boolean() | | DateTime | z.date() | | Json | z.any() | | BigInt | z.bigint() | | Decimal | z.number() | | Bytes | z.instanceof(Uint8Array) |

Field Modifiers

  • @default() - Adds .default() to the schema (when includeDefaults is true)
  • @unique - Adds validation for uniqueness
  • Optional fields (?) - Adds .nullable()
  • Required fields - No additional modifiers
  • Array fields ([]) - Wraps in z.array()

Examples

With Enums

const schema = `
enum Role {
  USER
  ADMIN
  MODERATOR
}

model User {
  id   Int  @id @default(autoincrement())
  role Role @default(USER)
}
`;

const result = convertPrismaToZod(schema);
// Generates RoleSchema and UserSchema with proper enum handling

With Relations

const schema = `
model User {
  id    Int    @id @default(autoincrement())
  posts Post[]
}

model Post {
  id       Int  @id @default(autoincrement())
  author   User @relation(fields: [authorId], references: [id])
  authorId Int
}
`;

const result = convertPrismaToZod(schema, { includeRelations: true });
// Includes relation fields in the generated schemas

With Custom Type Mappings

const schema = `
model User {
  id   Int  @id @default(autoincrement())
  uuid UUID
}
`;

const result = convertPrismaToZod(schema, {
  customMappings: {
    UUID: 'z.string().uuid()',
  },
});
// Uses custom UUID mapping

Generate Complete Files

import { generateSchemaFile } from 'prisma2zod';

const schema = `...`;
const completeFile = generateSchemaFile(schema, {
  includeRelations: true,
  includeDefaults: true,
});

// Outputs a complete TypeScript file with imports and all schemas

CLI Options

prisma2zod <input-file> [options]

Options:
  -o, --output <file>           Output file (default: stdout)
  -f, --format <single|separate> Output format (default: single)
  --no-types                    Don't generate TypeScript types
  --no-imports                  Don't include imports
  --no-enums                    Don't include enums
  --relations                   Include relation fields
  --defaults                    Include default values
  --help                        Show this help message

Development

Setup

npm install

Build

npm run build

Test

npm test

Lint

npm run lint

Format

npm run format

Project Structure

prisma2zod/
├── src/
│   ├── index.ts          # Main exports
│   ├── types.ts          # TypeScript interfaces
│   ├── parser.ts         # Prisma schema parser
│   ├── converter.ts      # Prisma to Zod converter
│   ├── generator.ts      # File generation utilities
│   ├── cli.ts           # Command line interface
│   └── __tests__/       # Test files
├── examples/             # Usage examples
├── dist/                # Compiled output
└── package.json

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Run the test suite
  6. Submit a pull request

License

MIT