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 liketitle String /// @zod.max(255, { message: "The title must be shorter than 256 characters" })becomesz.string().max(255, { message: ... }). - Imported helpers: Setting
imports = "../src/zod-schemas"in the generator config lets fields reference shared validators viaimports.isValidUsernameusing 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 likez.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:
- Add the generator as a dev dependency:
yarn add -D zod-prisma - Add the generator block to
schema.prisma, settingprovider = "zod-prisma"and anoutputdirectory. - Run
npx prisma generate(oryarn prisma generate) to emit the schemas. - 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.