← Back to archive

Repo of the Day

CarterGrimmeisen/zod-prisma

Published: Oct 31, 2022

Open repository ↗

Create zod schemas from prisma models

Summary

zod-prisma is a custom Prisma generator that produces Zod validation schemas directly from a project's schema.prisma file. Instead of maintaining Zod schemas by hand and updating them whenever a model changes, engineers get schemas generated alongside the Prisma client during prisma generate. It is written in TypeScript and distributed under the MIT license.

What it is useful for

Any TypeScript project that uses both Prisma for database access and Zod for runtime validation benefits from keeping the two in lockstep. zod-prisma is useful when you want to validate API request bodies, form input, or environment-derived data against the exact shape of your database models without writing and maintaining duplicate definitions.

Beyond plain schema generation, the tool supports several documented extensions:

  • JSDoc generation: Triple-slash (///) comments in the Prisma schema are converted into JSDoc on the generated Zod fields.
  • Field extensions with @zod: A model field like title String /// @zod.max(255, { message: "The title must be shorter than 256 characters" }) becomes z.string().max(255, { message: ... }).
  • Imported helpers: Setting imports = "../src/zod-schemas" in the generator config lets fields reference shared validators via imports.isValidUsername using the @zod.refine(imports.isValidUsername) directive.
  • Custom schemas: The @zod.custom(...) directive replaces the auto-generated schema for a field entirely, enabling use of constructs like z.preprocess.
  • JSON nullability: JSON fields disallow nulls by default to match Prisma's behavior; this can be relaxed via prismaJsonNullability = false.

One documented limitation worth noting: TypeScript's strict mode must be enabled in tsconfig.json, otherwise Zod-related type errors appear.

How engineers can use it

The README documents a four-step setup:

  1. Add the generator as a dev dependency:
    yarn add -D zod-prisma
    
  2. Add the generator block to schema.prisma, setting provider = "zod-prisma" and an output directory.
  3. Run npx prisma generate (or yarn prisma generate) to emit the schemas.
  4. Import the generated schemas from the configured output directory and use them like any other Zod object, for example when validating an incoming request body against PostModel.

For deeper usage examples, including relation models, decimal handling via useDecimalJs, and casing options, the README points to the examples/ directory and the functional tests in src/test/functional.