Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

♻️ Refactor prisma client to use database pool (#2138)

Luke Vella0120d8385625
diff --git a/.claude/rules/prisma.md b/.claude/rules/prisma.md
new file mode 100644
index 000000000..afc77b68a
--- /dev/null
+++ b/.claude/rules/prisma.md
@@ -0,0 +1,485 @@
+---
+description: Guidelines for writing Turborepo + Prisma Postgres apps (Prisma ORM v7)
+alwaysApply: false
+---
+
+# Bootstrap Turborepo with Prisma Postgres (Prisma v7)
+
+## Overview
+
+This guide bootstraps a Turborepo monorepo that shares a single Prisma ORM v7 database package across multiple apps (e.g., Next.js, Node APIs). It follows Turborepo and Prisma v7 best practices:
+
+1. Create a Turborepo with apps + packages
+2. Add a dedicated `packages/database` Prisma package (schema, migrations, generated client)
+3. Configure Prisma v7 (`provider = "prisma-client"` + mandatory `output`)
+4. Load env vars correctly in a monorepo
+5. Export a single Prisma client from `packages/database` for all apps
+6. Wire Turbo tasks for generate/migrate/test/studio
+7. Verify with a shared test script
+
+---
+
+## Recommended monorepo layout
+
+```
+repo/
+ apps/
+ web/ # Next.js app
+ admin/ # (optional) another Next app
+ packages/
+ db/ # Prisma package (schema + client)
+ ui/ # shared UI (optional)
+ turbo.json
+ package.json
+ .env # root env for apps (see notes)
+```
+
+**Key rule:** Prisma lives in `packages/database`, not inside an app, so every app consumes the same client and types.
+
+---
+
+## 🚨 CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS 🚨
+
+As an AI language model, you MUST NOT generate any deprecated Prisma v7 patterns.
+
+```prisma
+// ❌ NEVER GENERATE - DEPRECATED IN PRISMA v7
+generator client {
+ provider = "prisma-client-js" // ❌ deprecated
+}
+
+// ❌ NEVER IMPORT FROM @prisma/client when using custom output
+import { PrismaClient } from "@prisma/client" // ❌ wrong in custom-output setup
+
+// ❌ NEVER CREATE CLIENT WITHOUT SHARED PACKAGE BOUNDARY
+const prisma = new PrismaClient() // ❌ breaks pooling + duplicates in monorepo
+```
+
+Instead, you MUST ALWAYS generate ONLY this pattern for Prisma v7 + monorepo:
+
+```prisma
+// ✅ Prisma v7 generator: provider + mandatory output
+generator client {
+ provider = "prisma-client"
+ output = "../src/generated/prisma"
+}
+```
+
+```ts
+// ✅ Prisma client import must come from custom output
+import { PrismaClient } from "../generated/prisma/client"
+```
+
+Notes:
+- Prisma v7 **requires** a non-empty `output` when using `provider = "prisma-client"`.
+- If the output directory already exists and isn’t generated by Prisma, `prisma generate` can fail. Avoid committing generated client, or ensure clean output dirs.
+
+---
+
+## ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION
+
+1. You MUST use `provider = "prisma-client"` (Prisma v7)
+2. You MUST specify a custom `output` in `schema.prisma`
+3. You MUST place Prisma schema + migrations inside `packages/database`
+4. You MUST export a singleton Prisma client from `packages/database` that points to the generated output client file
+5. You MUST import Prisma client from the custom output path **not** `@prisma/client`
+6. You MUST load env vars in `packages/database/prisma.config.ts`
+7. You MUST add Turbo tasks for generate/migrate/test/studio
+8. You MUST wrap DB calls in try/catch in app code
+9. You MUST ensure Turbo task hashing includes `DATABASE_URL`
+10. You MUST create a shared test script in `packages/database/scripts/test-database.ts`
+
+---
+
+## Install dependencies
+
+At repo root:
+
+```bash
+# Turborepo
+npm install turbo --save-dev
+
+# Prisma v7
+npm install prisma tsx --save-dev
+npm install @prisma/client dotenv
+```
+
+If using Prisma Postgres:
+
+```bash
+npm install @prisma/adapter-pg
+```
+
+---
+
+## Initialize Prisma inside `packages/database`
+
+```bash
+cd packages/database
+npx prisma init
+```
+
+This creates:
+
+```
+packages/database/
+ prisma/
+ schema.prisma
+ prisma.config.ts
+```
+
+---
+
+## Prisma v7 config (`packages/database/prisma.config.ts`)
+
+**CRITICAL:** load env vars at the top.
+
+```ts
+import "dotenv/config"
+import { defineConfig, env } from "prisma/config"
+
+export default defineConfig({
+ schema: "prisma/schema.prisma",
+ migrations: {
+ path: "prisma/migrations",
+ },
+
+ datasource: {
+ url: env("DATABASE_URL"),
+ },
+})
+```
+
+---
+
+## Prisma schema (`packages/database/prisma/schema.prisma`)
+
+```prisma
+generator client {
+ provider = "prisma-client"
+ output = "../src/generated/prisma"
+}
+
+datasource db {
+ provider = "postgresql"
+}
+
+model User {
+ id Int @id @default(autoincrement())
+ email String @unique
+ name String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+}
+```
+
+---
+
+## Shared Prisma client singleton (`packages/database/src/client.ts`)
+
+```ts
+import { PrismaClient } from "../generated/prisma/client"
+
+//Prisma Driver Adapter for Postgres
+import { PrismaPg } from '@prisma/adapter-pg'
+
+
+
+// Create a new Driver Adapter instance for PrismaPostgres
+const adapter = new PrismaPg({
+ connectionString: process.env.DATABASE_URL!,
+})
+
+
+const globalForPrisma = globalThis as unknown as {
+ prisma?: PrismaClient
+}
+
+export const prisma =
+ globalForPrisma.prisma ??
+ new PrismaClient({ adapter })
+
+if (process.env.NODE_ENV !== "production") {
+ globalForPrisma.prisma = prisma
+}
+
+export default prisma
+```
+
+---
+
+## Export DB package API (`packages/database/src/index.ts`)
+
+```ts
+export { prisma } from "./client"
+export * from "../generated/prisma"
+```
+
+And in `packages/database/package.json`:
+
+```json
+{
+ "name": "@repo/db",
+ "private": true,
+ "main": "src/index.ts",
+ "types": "src/index.ts",
+ "scripts": {
+ "db:generate": "prisma generate",
+ "db:push": "prisma db push",
+ "db:migrate": "prisma migrate dev",
+ "db:studio": "prisma studio",
+ "db:test": "tsx scripts/test-database.ts"
+ }
+}
+```
+
+---
+
+## Root Turbo pipeline (`turbo.json`)
+
+```json
+{
+ "globalEnv": ["DATABASE_URL"],
+ "tasks": {
+ "dev": {
+ "cache": false,
+ "persistent": true,
+ "dependsOn": ["^db:generate"]
+ },
+ "build": {
+ "dependsOn": ["^db:generate"],
+ "outputs": [".next/**", "dist/**"]
+ },
+ "db:generate": {
+ "cache": false
+ },
+ "db:migrate": {
+ "cache": false
+ },
+ "db:studio": {
+ "cache": false
+ },
+ "db:test": {
+ "cache": false,
+ "dependsOn": ["db:generate"]
+ }
+ }
+}
+```
+
+---
+
+## Root scripts (`package.json`)
+
+```json
+{
+ "scripts": {
+ "dev": "turbo dev",
+ "build": "turbo build",
+ "lint": "turbo lint",
+ "db:generate": "turbo run db:generate",
+ "db:push": "turbo run db:push",
+ "db:migrate": "turbo run db:migrate",
+ "db:studio": "turbo run db:studio",
+ "db:test": "turbo run db:test"
+ }
+}
+```
+
+---
+
+## Shared test script (`packages/database/scripts/test-database.ts`)
+
+```ts
+import "dotenv/config"
+import prisma from "../src/client"
+
+async function testDatabase() {
+ console.log("🔍 Testing Prisma Postgres connection...\n")
+
+ try {
+ console.log("✅ Connected to database!")
+
+ console.log("\n📝 Creating a test user...")
+ const newUser = await prisma.user.create({
+ data: {
+ email: "[email protected]",
+ name: "Demo User"
+ }
+ })
+ console.log("✅ Created user:", newUser)
+
+ console.log("\n📋 Fetching all users...")
+ const allUsers = await prisma.user.findMany()
+ console.log(`✅ Found ${allUsers.length} user(s):`)
+ allUsers.forEach((user) => {
+ console.log(` - ${user.name} (${user.email})`)
+ })
+
+ console.log("\n🎉 All tests passed! Your database is working.\n")
+ } catch (error) {
+ console.error("❌ Error:", error)
+ process.exit(1)
+ } finally {
+ await prisma.$disconnect()
+ }
+}
+
+testDatabase()
+```
+
+---
+
+## Using Prisma in apps (example: `apps/web` Next.js)
+
+In any app, add a dependency on `@repo/db` (workspace):
+
+```json
+{
+ "dependencies": {
+ "@repo/db": "*"
+ }
+}
+```
+
+Then in server-side code:
+
+```ts
+import { prisma } from "@repo/db"
+import { NextResponse } from "next/server"
+
+export async function GET() {
+ try {
+ const users = await prisma.user.findMany()
+ return NextResponse.json(users)
+ } catch (e) {
+ console.error(e)
+ return NextResponse.json({ error: "Failed to fetch users" }, { status: 500 })
+ }
+}
+```
+
+---
+
+## Complete setup workflow
+
+1. **Create Turborepo** (or use existing):
+ ```bash
+ npx create-turbo@latest
+ ```
+
+2. **Add `packages/database`**, install Prisma v7 deps.
+
+3. **Initialize Prisma in `packages/database`**:
+ ```bash
+ cd packages/database
+ npx prisma init
+ ```
+
+4. **Update `prisma.config.ts`** to include `import "dotenv/config"`.
+
+5. **Update schema** with Prisma v7 generator + output.
+
+6. **Create `src/client.ts`** singleton and export via `src/index.ts`.
+
+7. **Wire Turbo tasks** in `turbo.json`.
+
+8. **Add `.env`** at root **and/or** `packages/database/.env`.
+
+9. **Push schema**:
+ ```bash
+ npm run db:push
+ ```
+
+10. **Test**:
+ ```bash
+ npm run db:test
+ ```
+
+11. **Start dev**:
+ ```bash
+ npm run dev
+ ```
+
+---
+
+## AI Model verification checklist
+
+Before generating any code, verify:
+
+1. `provider = "prisma-client"`?
+2. `output = "../src/generated/prisma"` present?
+3. All Prisma files in `packages/database`?
+4. Client imports from `../generated/prisma/client` (or via `@repo/db`)?
+5. `import "dotenv/config"` in `packages/database/prisma.config.ts`?
+6. Turbo tasks depend on `db:generate`?
+7. `DATABASE_URL` listed in `globalEnv`?
+8. All DB ops wrapped in try/catch?
+9. Test script exists in `packages/database/scripts/test-database.ts`?
+
+No exceptions. If any check fails, STOP and FIX.
+
+---
+
+## AI MODEL RESPONSE TEMPLATE (UPDATED FOR TURBOREPO + PRISMA v7)
+
+When asked about implementing Prisma v7 inside a Turborepo monorepo (with any framework such as Next.js, Node, etc.), you MUST:
+
+1. **Assume Prisma lives in a shared package**
+ - Always place schema, config, and migrations in `packages/database`.
+ - Never suggest adding Prisma directly into an app unless the user explicitly says they don’t want a shared package.
+
+2. **Use only Prisma v7 generator patterns**
+ - The schema MUST include:
+ ```prisma
+ generator client {
+ provider = "prisma-client"
+ output = "./generated/prisma"
+ }
+ ```
+ - Never use `prisma-client-js`.
+
+3. **Use correct import paths for custom output**
+ - Any PrismaClient import MUST come from the generated output:
+ ```ts
+ import { PrismaClient } from "./generated/prisma/client"
+ ```
+ - If importing from apps, you MUST import via the package boundary:
+ ```ts
+ import { prisma } from "@repo/db"
+ ```
+ - Never import from `@prisma/client` in this setup.
+
+4. **Always include a shared singleton client in `packages/database`**
+ - Provide a `packages/database/src/client.ts` with global caching for dev hot-reload.
+ - If Accelerate is requested or implied, use `$extends(withAccelerate())`.
+ - If Accelerate is not requested, omit it.
+
+5. **Always load environment variables properly**
+ - `packages/database/prisma.config.ts` MUST start with `import "dotenv/config"`.
+ - Use `process.env.DATABASE_URL` in runtime code.
+ - Remind users that `.env` should exist at root and/or `packages/database`.
+
+6. **Always wire Turbo dependencies**
+ - Turbo tasks `dev` and `build` MUST depend on `^db:generate`.
+ - `DATABASE_URL` MUST be listed in `globalEnv` to ensure correct task hashing.
+
+7. **Provide correct repo-level scripts**
+ - Root scripts should proxy to Turbo (`turbo run db:*`).
+ - The Prisma package `packages/database` should own `db:generate`, `db:migrate`, `db:studio`, and `db:test`.
+
+8. **Include a real verification step**
+ - Provide (or reference) `packages/database/scripts/test-database.ts`.
+ - Ensure it imports dotenv and disconnects Prisma on completion.
+
+9. **Use safe runtime patterns**
+ - All DB calls in apps MUST be wrapped in try/catch.
+ - In Next.js App Router examples, use server-only imports and return `NextResponse`.
+
+10. **Self-verify before replying**
+ - Re-check all items in the “AI Model verification checklist.”
+ - If any item is missing or incorrect, STOP and FIX before responding.
+
+Remember: There are NO exceptions to these rules. Every requirement is mandatory for a correct Turborepo + Prisma v7 setup.
+
+
diff --git a/apps/web/package.json b/apps/web/package.json
index f4db9d8f7..25dafabf1 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -58,7 +58,7 @@
"@trpc/server": "^11.8.0",
"@upstash/qstash": "^2.7.17",
"@upstash/ratelimit": "^1.2.1",
- "@vercel/functions": "^2.0.0",
+ "@vercel/functions": "^3.3.6",
"@vercel/kv": "^3.0.0",
"ai": "^5.0.41",
"arctic": "^3.7.0",
diff --git a/packages/database/index.ts b/packages/database/index.ts
deleted file mode 100644
index 5e11aa865..000000000
--- a/packages/database/index.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { PrismaPg } from "@prisma/adapter-pg";
-import { PrismaClient } from "./generated/prisma/client";
-
-export type * from "./generated/prisma/client";
-
-const prismaClientSingleton = () => {
- const connectionString = process.env.DATABASE_URL;
- const adapter = new PrismaPg({ connectionString });
- return new PrismaClient({ adapter });
-};
-
-export type ExtendedPrismaClient = ReturnType<typeof prismaClientSingleton>;
-
-// biome-ignore lint/suspicious/noShadowRestrictedNames: Fix this later
-declare const globalThis: {
- prismaGlobal: ExtendedPrismaClient;
-} & typeof global;
-
-const prisma = globalThis.prismaGlobal ?? prismaClientSingleton();
-
-export { prisma };
-
-if (process.env.NODE_ENV !== "production") globalThis.prismaGlobal = prisma;
diff --git a/packages/database/package.json b/packages/database/package.json
index 9658d52c7..080a9d55c 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -11,11 +11,12 @@
"type-check": "tsc --pretty --noEmit"
},
"exports": {
- ".": "./index.ts"
+ ".": "./src/client.ts"
},
"dependencies": {
"@prisma/adapter-pg": "^7.2.0",
"@prisma/client": "^7.2.0",
+ "@vercel/functions": "^3.3.6",
"dayjs": "^1.11.13",
"pg": "^8.17.1"
},
diff --git a/packages/database/prisma/seed.ts b/packages/database/prisma/seed.ts
index 6fb24d62f..32b5e69f2 100644
--- a/packages/database/prisma/seed.ts
+++ b/packages/database/prisma/seed.ts
@@ -1,4 +1,4 @@
-import { prisma } from "../";
+import { prisma } from "@rallly/database";
import { seedPolls } from "./seed/polls";
import { seedScheduledEvents } from "./seed/scheduled-events";
import { seedUsers } from "./seed/users";
diff --git a/packages/database/src/client.ts b/packages/database/src/client.ts
new file mode 100644
index 000000000..2ef5bde32
--- /dev/null
+++ b/packages/database/src/client.ts
@@ -0,0 +1,26 @@
+import { PrismaPg } from "@prisma/adapter-pg";
+import { attachDatabasePool } from "@vercel/functions";
+import { Pool } from "pg";
+import { PrismaClient } from "../generated/prisma/client";
+
+export type * from "../generated/prisma/client";
+
+const pool = new Pool({ connectionString: process.env.DATABASE_URL });
+
+attachDatabasePool(pool);
+
+const globalForPrisma = globalThis as unknown as {
+ prisma?: PrismaClient;
+};
+
+export const prisma =
+ globalForPrisma.prisma ??
+ new PrismaClient({
+ adapter: new PrismaPg(pool),
+ });
+
+if (process.env.NODE_ENV !== "production") {
+ globalForPrisma.prisma = prisma;
+}
+
+export default prisma;
diff --git a/packages/emails/package.json b/packages/emails/package.json
index f630416ce..45246f956 100644
--- a/packages/emails/package.json
+++ b/packages/emails/package.json
@@ -16,7 +16,7 @@
"@aws-sdk/credential-provider-node": "^3.501.0",
"@react-email/components": "^0.0.36",
"@react-email/render": "^1.0.6",
- "@vercel/functions": "^2.0.0",
+ "@vercel/functions": "^3.3.6",
"i18next": "^24.2.2",
"i18next-icu": "^2.3.0",
"i18next-resources-to-backend": "^1.2.1",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 461791062..da98a9495 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -299,8 +299,8 @@ importers:
specifier: ^1.2.1
version: 1.2.1
'@vercel/functions':
- specifier: ^2.0.0
- version: 2.0.0(@aws-sdk/[email protected])
+ specifier: ^3.3.6
+ version: 3.3.6(@aws-sdk/[email protected])
'@vercel/kv':
specifier: ^3.0.0
version: 3.0.0
@@ -543,6 +543,9 @@ importers:
'@prisma/client':
specifier: ^7.2.0
+ '@vercel/functions':
+ specifier: ^3.3.6
+ version: 3.3.6(@aws-sdk/[email protected])
dayjs:
specifier: ^1.11.13
version: 1.11.13
@@ -586,8 +589,8 @@ importers:
specifier: ^1.0.6
'@vercel/functions':
- specifier: ^2.0.0
- version: 2.0.0(@aws-sdk/[email protected])
+ specifier: ^3.3.6
+ version: 3.3.6(@aws-sdk/[email protected])
i18next:
specifier: ^24.2.2
version: 24.2.3([email protected])
@@ -5159,9 +5162,9 @@ packages:
vue-router:
optional: true
- '@vercel/[email protected]':
- resolution: {integrity: sha512-BSwIihLHoV18gerKZJyGuqd3rtaYM6rJvET1kOwKktshucyaHXTJel7Cxegs+sdX0NZqsX4LO2MFnMU2jG01Cw==}
- engines: {node: '>= 18'}
+ '@vercel/[email protected]':
+ resolution: {integrity: sha512-mLKK3H+v1XjzTiksYN7XV4sl/n8tqb0DeavoUzjFKRQMmx5x+vy1jIl24GY4C8D2dinQPV1ZuCSPhJptBeeE/A==}
+ engines: {node: '>= 20'}
peerDependencies:
'@aws-sdk/credential-provider-web-identity': '*'
peerDependenciesMeta:
@@ -5172,6 +5175,10 @@ packages:
resolution: {integrity: sha512-pKT8fRnfyYk2MgvyB6fn6ipJPCdfZwiKDdw7vB+HL50rjboEBHDVBEcnwfkEpVSp2AjNtoaOUH7zG+bVC/rvSg==}
engines: {node: '>=14.6'}
+ '@vercel/[email protected]':
+ resolution: {integrity: sha512-Fw28YZpRnA3cAHHDlkt7xQHiJ0fcL+NRcIqsocZQUSmbzeIKRpwttJjik5ZGanXP+vlA4SbTg+AbA3bP363l+w==}
+ engines: {node: '>= 20'}
+
'@vitejs/[email protected]':
resolution: {integrity: sha512-Jx9JfsTa05bYkS9xo0hkofp2dCmp1blrKjw9JONs5BTHOvJCgLbaPSuZLGSVJW6u2qe0tc4eevY0+gSNNi0YCw==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -15850,7 +15857,9 @@ snapshots:
react: 19.2.1
- '@vercel/[email protected](@aws-sdk/[email protected])':
+ '@vercel/[email protected](@aws-sdk/[email protected])':
+ dependencies:
+ '@vercel/oidc': 3.1.0
optionalDependencies:
'@aws-sdk/credential-provider-web-identity': 3.797.0
@@ -15858,6 +15867,8 @@ snapshots:
dependencies:
'@upstash/redis': 1.34.8
+ '@vercel/[email protected]': {}
+
dependencies:
'@babel/core': 7.28.3