Skip to Content
hono-bento

Prisma and Postgres

Set up a db package with Prisma 7 and Postgres, wire it into handlers through deps, and run it locally and in CI.

This is the setup the example monorepo uses.

Create the db package

schema.prisma
client.ts
seed.ts
prisma.config.ts
package.json
bun add @prisma/client @prisma/adapter-pg @prisma/client-runtime-utils pg dotenv
bun add --dev prisma @types/pg

@prisma/client-runtime-utils is needed when your package manager isolates dependencies (Bun's default linker, pnpm), because the generated client imports it.

packages/db/package.json
{
  "name": "@todos/db",
  "private": true,
  "type": "module",
  "exports": { ".": "./src/client.ts" },
  "scripts": {
    "postinstall": "prisma generate",
    "migrate": "prisma migrate deploy",
    "migrate:dev": "prisma migrate dev",
    "seed": "bun --env-file=../../.env src/seed.ts"
  }
}

Add /generated to the package's .gitignore. postinstall regenerates the client on every install.

Describe the models

packages/db/prisma/schema.prisma
datasource db {
  provider = "postgresql"
}

generator client {
  provider = "prisma-client-js"
  output   = "../generated/client"
}

model Todo {
  id        String   @id
  title     String
  done      Boolean  @default(false)
  createdAt DateTime @default(now())

  @@index([createdAt])
}

These are storage models. The API's wire shapes stay in @todos/schemas.

Configure Prisma

packages/db/prisma.config.ts
import path from 'node:path';
import { fileURLToPath } from 'node:url';

import { config } from 'dotenv';
import { defineConfig, env } from 'prisma/config';

config({ path: path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../.env'), quiet: true });

export default defineConfig({
  schema: 'prisma/schema.prisma',
  migrations: { path: 'prisma/migrations', seed: 'bun --env-file=../../.env src/seed.ts' },
  // `prisma generate` needs no database, so installs work without DATABASE_URL.
  ...(process.env.DATABASE_URL ? { datasource: { url: env('DATABASE_URL') } } : {}),
});

Export the client

packages/db/src/client.ts
import { PrismaPg } from '@prisma/adapter-pg';
import { Pool } from 'pg';

import { PrismaClient } from '../generated/client';

export type Database = PrismaClient;

/** Called once per process, by server.ts and tests. Features never call it. */
export function createDatabase(url: string): Database {
  return new PrismaClient({ adapter: new PrismaPg(new Pool({ connectionString: url })) });
}

export * from '../generated/client';

Run Postgres locally

docker-compose.yml
services:
  db:
    image: postgres:17
    environment:
      POSTGRES_USER: todos
      POSTGRES_PASSWORD: todos
      POSTGRES_DB: todos
    ports:
      - '5433:5432'
    healthcheck:
      test: ['CMD', 'pg_isready', '-U', 'todos', '-d', 'todos']
      interval: 2s
      retries: 15
.env
DATABASE_URL=postgresql://todos:todos@localhost:5433/todos
docker compose up -d --wait
bun run --cwd packages/db migrate:dev --name init   # creates and applies the first migration

Commit prisma/migrations/. Deploys run prisma migrate deploy.

Wire it into the API

Register Deps, pass the database to createApp, and map Prisma's errors. See Database for each piece:

apps/api/src/deps.ts
import type { Database } from '@todos/db';

import type { ChangeFeed, TodoChange } from './changes';

export interface Deps {
  db: Database;
  /** Changes to todos, which the todos feature publishes and its `changes` stream sends. */
  todoChanges: ChangeFeed<TodoChange>;
}

declare module 'hono-bento' {
  interface Register {
    deps: Deps;
  }
}
apps/api/src/app.ts
mountSpecs(app, specs, { strategies, authorizer, deps: () => deps, mapError: mapPrismaError });

Close the pool on shutdown:

apps/api/src/server.ts
process.on('SIGTERM', async () => {
  server.close();
  await db.$disconnect();
  process.exit(0);
});

Run it in CI

Give the job a Postgres service and migrate before the tests:

.github/workflows/ci.yml
jobs:
  check:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:17
        env: { POSTGRES_USER: todos, POSTGRES_PASSWORD: todos, POSTGRES_DB: todos }
        ports: ['5433:5432']
        options: --health-cmd "pg_isready -U todos -d todos" --health-interval 2s --health-retries 15
    env:
      DATABASE_URL: postgresql://todos:todos@localhost:5433/todos
    steps:
      # ...checkout, setup, install (which runs prisma generate)
      - run: bun run --cwd packages/db migrate
      - run: bun test

On this page