Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

prisma-trpc-generator

> 数据库
Open source

Prisma 2+ generator to emit fully implemented tRPC routers

738 stars0 likes1 views
WebsiteGitHub

About

Prisma 2+ generator to emit fully implemented tRPC routers

⚡ Prisma tRPC Generator

Automatically generate fully implemented, type-safe tRPC routers from your Prisma schema.

= 20.19.0 (min) · 22.x (rec)"> = 7.0.0 (min) · Latest 7.x (rec)"> = 5.4.0 (min) · 5.9.x (rec)">

Zero‑config • ️ Type‑safe • ⚡ Fast • Customizable

Transforms your Prisma schema into production‑ready tRPC APIs with Zod validation, middleware, and optional tRPC Shield.

✨ Key features

  • Zero configuration defaults
  • Always in sync with your Prisma schema
  • ️ 100% TypeScript type-safety
  • Complete CRUD coverage for all Prisma operations
  • ⚙️ Highly configurable: paths, middleware, shield, options
  • Lightweight and fast generation
  • Integrates with Zod, tRPC Shield, and custom middleware

Table of contents

  • Quick start
  • ⚙️ Configuration
  • Feature guide
    • Zod validation
    • Middleware & Shield
    • Auth
    • Request ID + logging
    • tRPC Metadata Support
    • OpenAPI (MVP)
    • Postman collection
    • DDD services (optional)
    • Migration from inline config
  • Generated output
  • ️ Advanced usage
  • Troubleshooting, performance, FAQ
  • Contributing
  • License
  • Related projects
  • Acknowledgments

Quick start

Requirements

Component Minimum Recommended
Node.js 20.19.0 22.x
Prisma 7.0.0 Latest 7.x
TypeScript 5.4.0 5.9.x

Install

bash
# npm
npm install prisma-trpc-generator

# yarn
yarn add prisma-trpc-generator

# pnpm
pnpm add prisma-trpc-generator

Configure Prisma 7

  1. Create prisma.config.ts at the repo root:

    typescript
    import 'dotenv/config';
    import { defineConfig, env } from 'prisma/config';
    
    export default defineConfig({
      schema: 'prisma/schema.prisma',
      migrations: {
        path: 'prisma/migrations',
        seed: 'tsx prisma/seed.ts',
      },
      datasource: {
        url: env('DATABASE_URL'),
      },
    });
  2. Update your generator client block:

    prisma
    generator client {
      provider = "prisma-client"
      output   = "../node_modules/.prisma/client"
    }
  3. Set DATABASE_URL (e.g., file:./prisma/dev.db) in .env and instantiate PrismaClient with the adapter that matches your database (SQLite → @prisma/adapter-better-sqlite3, Postgres → @prisma/adapter-pg, etc.).

Minimal setup

Add the generator to your Prisma schema and point to your JSON config file:

prisma
generator trpc {
  provider = "prisma-trpc-generator"
  output   = "./generated"
  config   = "./trpc.config.json"
}

Both output and config are resolved relative to the schema file, the way Prisma resolves generator paths. With the schema at prisma/schema.prisma, the block above reads prisma/trpc.config.json and writes to prisma/generated.

Create that config file (see Feature guide for options), enable "strict": true in tsconfig.json, then generate:

bash
npx prisma generate

⚙️ Configuration

As of v2.x, configuration is unified via a single JSON file. Your Prisma generator block should only specify output and config.

Example prisma/trpc.config.json:

{
  "withZod": true,
  "withMiddleware": true,
  "withShield": "./shield",
  "contextPath": "./context",
  "trpcOptionsPath": "./trpcOptions",
  "dateTimeStrategy": "date",
  "withMeta": false,
  "postman": true,
  "postmanExamples": "skeleton",
  "openapi": true,
  "withRequestId": false,
  "withLogging": false,
  "withServices": false,
  "showModelNameInProcedure": true
}

Notes

  • The config path is resolved relative to the Prisma schema file.
  • showModelNameInProcedure controls whether the model name is appended to each procedure. It defaults to true, giving createOneUser and aggregateUser. Set it to false for createOne and aggregate, which reads better when the procedures already sit under a per-model router.
  • Aliases configPath and configFile are also accepted.
  • If a config file is provided, any inline options in the generator block are ignored with a warning.
  • Inline options without a config file still work for now but are deprecated and will be removed in a future major release.

Feature guide

Each feature is opt‑in via the JSON config. Below are concise how‑tos and the exact keys to set.

1) Zod validation (inputs)

  • Key: withZod: true
  • Emits schemas/ with Zod types for procedure inputs; routers wire .input() automatically.
  • Date handling: Set dateTimeStrategy to control DateTime field validation:
    • "date" (default): z.date() - accepts only Date objects
    • "coerce": z.coerce.date() - accepts both Date objects and ISO strings
    • "isoString": ISO string validation with transformation

Extending Zod schemas with Prisma comments

You can add additional Zod validation constraints using special comments in your Prisma schema:

…

This generates Zod schemas with the specified validations:

typescript
export const UserCreateInput = z.object({
  id: z.number().int(),
  email: z.string().email(),
  name: z.string().min(1).max(100).nullish(),
  age: z.number().int().min(0).max(120).nullish(),
  // ...
});

For more advanced Zod validation options and syntax, see the prisma-zod-generator documentation.

2) Middleware & Shield

  • Keys: withMiddleware: boolean | string, withShield: boolean | string
  • When withMiddleware: true, a basic middleware scaffold is included; or point to your own path string.
  • When withShield is truthy, the generator imports your permissions and exposes shieldedProcedure in createRouter.ts.

3) Auth (session / JWT / custom)

  • Key: auth: boolean | { strategy?: 'session'|'jwt'|'custom'; rolesField?: string; jwt?: {...}; session?: {...}; custom?: {...} }
  • When enabled, generator emits:
    • routers/helpers/auth-strategy.ts (stubs + default HS256 JWT verifier)
    • routers/helpers/auth.ts with ensureAuth and ensureRole
    • createRouter.ts wires authMiddleware, publicProcedure, protectedProcedure, roleProcedure(roles)
  • See docs/usage/auth.md for strategy hooks and examples.

4) Request ID + logging

  • Keys: withRequestId: boolean, withLogging: boolean
  • Adds a small requestId middleware and optional structured log line around every procedure.
  • To propagate requestId into errors, return it in your trpcOptions.errorFormatter.

5) tRPC Metadata Support

  • Key: withMeta: boolean | { openapi?: boolean; auth?: boolean; description?: boolean; defaultMeta?: object }
  • When enabled, adds .meta() calls to generated procedures with:
    • OpenAPI-compatible metadata (HTTP methods, paths, tags, descriptions)
    • Authentication metadata for middleware integration
    • Custom metadata via defaultMeta configuration
  • Perfect for OpenAPI documentation, conditional auth, and enhanced middleware

6) OpenAPI (MVP)

  • Key: openapi: boolean | { enabled?: boolean; title?: string; version?: string; baseUrl?: string; pathPrefix?: string; pathStyle?: 'slash'|'dot'; includeExamples?: boolean }
  • Emits openapi/openapi.json and routers/adapters/openapi.ts with a tagged document.
  • Paths map to tRPC endpoints (POST) with a { input: {} } request body schema and optional skeleton examples.

7) Postman collection

  • Key: postman: boolean | { endpoint?: string; envName?: string; fromOpenApi?: boolean; examples?: 'none'|'skeleton' }
  • Emits postman/collection.json. When fromOpenApi: true, the collection is derived from OpenAPI.
  • Set examples: 'skeleton' to include sample bodies for common operations.

8) DDD services (optional)

  • Keys: withServices, serviceStyle, serviceDir, withListMethod, serviceImports
  • Emits a BaseService and per‑model service stubs; routers can delegate to services when enabled.
  • Tenancy/soft‑delete helpers are included in the service layer if you choose to use it.

Migration from inline config

  1. Create prisma/trpc.config.json and move all previous inline keys into it.
  2. Replace keys in generator trpc so it only contains output and config.
  3. Run generation. If you still have inline keys, the generator will ignore them and warn.

Generated output

Show generated layout

For the following schema:

prisma
model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

model Post {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  title     String
  content   String?
  published Boolean  @default(false)
  viewCount Int      @default(0)
  author    User?    @relation(fields: [authorId], references: [id])
  authorId  Int?
}

The generator creates:

generated/
├── routers/
│   ├── index.ts              # Main app router combining all model routers
│   ├── helpers/
│   │   └── createRouter.ts   # Base router factory with middleware/shield setup
│   ├── User.router.ts        # User CRUD operations
│   └── Post.router.ts        # Post CRUD operations
└── schemas/                  # Zod validation schemas (if withZod: true)
    ├── objects/              # Input type schemas
    ├── findManyUser.schema.ts
    ├── createOneUser.schema.ts
    └── index.ts              # Barrel exports

️ Advanced usage

Show advanced usage examples

Custom middleware

typescript
// src/middleware.ts
import { TRPCError } from '@trpc/server';
import { t } from './trpc';

export const authMiddleware = t.middleware(async ({ ctx, next }) => {
  if (!ctx.user) {
    throw new TRPCError({ code: 'UNAUTHORIZED' });
  }
  return next({
    ctx: {
      ...ctx,
      user: ctx.user,
    },
  });
});

export const loggingMiddleware = t.middleware(async ({ path, type, next }) => {
  console.log(`tRPC ${type} ${path}`);
  return next();
});

Integration with tRPC Shield

…

Custom tRPC options

typescript
// src/trpcOptions.ts
import { ZodError } from 'zod';
import superjson from 'superjson';

export default {
  transformer: superjson,
  errorFormatter({ shape, error }) {
    return {
      ...shape,
      data: {
        ...shape.data,
        zodError:
          error.code === 'BAD_REQUEST' && error.cause instanceof ZodError
            ? error.cause.flatten()
            : null,
      },
    };
  },
};

Customizations

Skipping models

prisma
/// @@Gen.model(hide: true)
model InternalLog {
  id        Int      @id @default(autoincrement())
  message   String
  createdAt DateTime @default(now())
}

Custom context

typescript
// src/context.ts
import 'dotenv/config';
import { PrismaClient } from '@prisma/client';
import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3';

const adapter = new PrismaBetterSqlite3({
  url: process.env.DATABASE_URL as ':memory:' | (string & {}),
});
const prisma = new PrismaClient({ adapter });

export interface Context {
  prisma: PrismaClient;
  user?: { id: string; email: string; role: string };
}

export const createContext = async ({ req }): Promise => {
  const user = await getUserFromRequest(req);
  return { prisma, user };
};

Examples

Basic CRUD with authentication

…

Next.js App Router integration

typescript
// src/app/api/trpc/[trpc]/route.ts
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import { appRouter } from '@/server/api/root';
im

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptprismaprisma-generatortrpczod

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库