Cursor rule for Prisma 7 with the prisma-client generator, prisma.config.ts, driver adapters, selective queries, transactions, cursor pagination and $extends soft delete.
.cursor/rules/prisma-orm-best-practices.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for Prisma 7 with the prisma-client generator, prisma.config.ts, driver adapters, selective queries, transactions, cursor pagination and $extends soft delete."
globs: "**/*"
alwaysApply: false
---
# Prisma ORM Best Practices
Applies to: `schema.prisma`, `prisma.config.ts`, migrations and Prisma Client queries in a TypeScript project.
Version baseline: checked against the Prisma ORM 7 documentation and upgrade guide. Read `package.json` first. If the project is still on Prisma 5 or 6, keep its existing generator and datasource style and follow the upgrade guide before adopting the Prisma 7 patterns below.
## Prisma 7 setup facts
- Use the `prisma-client` generator with an explicit `output`; the client is no longer generated into `node_modules`. `prisma-client-js` is deprecated.
- Connection URLs live in `prisma.config.ts`, not in the `datasource` block; Prisma 7 rejects `url = env(...)` in the schema.
- Prisma Client is created with a driver adapter (for PostgreSQL, `@prisma/adapter-pg`). Environment variables are not loaded automatically; load them (for example `import 'dotenv/config'`) where the config is read.
- The `$use` middleware API is removed. Use Client Extensions (`$extends`).
## Schema
```prisma
generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
}
datasource db {
provider = "postgresql"
}
model User {
id String @id @default(cuid())
email String @unique
name String?
role Role @default(USER)
posts Post[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@map("users")
}
model Post {
id String @id @default(cuid())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
authorId String
tags Tag[]
deletedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([authorId])
@@index([published, createdAt])
@@map("posts")
}
model Tag {
id String @id @default(cuid())
name String @unique
posts Post[]
@@map("tags")
}
enum Role {
USER
ADMIN
}
```
- `@unique` already creates an index; do not add a duplicate `@@index` on the same column.
- Index foreign keys used in filters and the column combinations used in `where` + `orderBy`. Confirm with `EXPLAIN` on real queries rather than indexing every column.
- Choose `onDelete` per relation deliberately (`Cascade`, `Restrict`, `SetNull`) and document why.
- Store password hashes only, in a field or table the API never selects by default.
```ts
// prisma.config.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') },
})
```
`env()` throws when the variable is unset, so every Prisma CLI command (including `generate` and `validate`) needs `DATABASE_URL` present, for example a placeholder value in CI jobs that only generate the client. If that is a problem, read `process.env.DATABASE_URL` instead and let commands that need a connection fail on their own.
## Client instance
Create one client per process and reuse it (in Next.js dev, cache it on `globalThis` to survive hot reload).
```ts
// src/lib/prisma.ts
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from '../generated/prisma/client'
export const prisma = new PrismaClient({
adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
})
```
## Query patterns
- Use `select` to return only needed fields (and never the password hash); use `include` only when you need the whole related records.
- Avoid N+1 loops: fetch relations with `include`/`select` or a single `findMany({ where: { id: { in: ids } } })`.
- Use the array form of `$transaction` for independent writes that must commit together, and the interactive form when later steps depend on earlier reads. Keep interactive transactions short and free of network calls.
```ts
// src/posts.ts
import { prisma } from './lib/prisma'
export async function publishFirstDraft(authorId: string) {
return prisma.$transaction(async (tx) => {
const draft = await tx.post.findFirst({
where: { authorId, published: false, deletedAt: null },
orderBy: { createdAt: 'asc' },
select: { id: true },
})
if (!draft) return null
return tx.post.update({ where: { id: draft.id }, data: { published: true } })
})
}
export async function listPosts(page: number, limit: number) {
const where = { published: true, deletedAt: null }
const [data, total] = await prisma.$transaction([
prisma.post.findMany({ where, skip: (page - 1) * limit, take: limit, orderBy: { createdAt: 'desc' } }),
prisma.post.count({ where }),
])
return { data, total, totalPages: Math.ceil(total / limit) }
}
export async function listPostsAfter(cursor: string | undefined, limit = 20) {
const rows = await prisma.post.findMany({
where: { published: true, deletedAt: null },
take: limit + 1,
...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
})
const hasMore = rows.length > limit
const data = hasMore ? rows.slice(0, limit) : rows
return { data, nextCursor: hasMore ? data[data.length - 1]?.id ?? null : null }
}
```
Prefer cursor pagination for large or frequently changing tables; order by a unique tie-breaker (`id`) so pages are stable.
## Soft delete with a Client Extension
Replace the removed `$use` middleware with a query extension, and keep the filter visible in reads:
```ts
// src/lib/soft-delete.ts
import { prisma } from './prisma'
export const db = prisma.$extends({
model: {
post: {
async softDelete(id: string) {
return prisma.post.update({ where: { id }, data: { deletedAt: new Date() } })
},
},
},
query: {
post: {
async findMany({ args, query }) {
args.where = { deletedAt: null, ...args.where }
return query(args)
},
},
},
})
```
Unique lookups (`findUnique`) and aggregates are not covered by this `findMany` hook; filter `deletedAt: null` explicitly there or extend those operations too.
## Migrations
- Change the schema, then `npx prisma migrate dev --name <change>` locally; commit the generated SQL.
- Deploy with `npx prisma migrate deploy`; never run `migrate dev` or `db push` against production.
- Review generated SQL for destructive steps (dropped columns, type changes) and split risky changes into expand/migrate/contract releases.
## Verify before finishing
- `npx prisma validate` and `npx prisma format` pass.
- `npx prisma generate` then `npx tsc --noEmit` pass (`validate` does not report a missing generator `output`; `generate` does).
- For schema changes, `npx prisma migrate dev` against a local or disposable database produces the expected SQL.
- Queries you added return only selected fields (check the TypeScript result type).
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
database
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
Upgrading a Prisma 6 PostgreSQL project to Prisma 7 and replacing a $use soft-delete middleware.
schema.prisma uses provider = "prisma-client-js" and url = env("DATABASE_URL"); lib/prisma.ts does new PrismaClient(); a prisma.$use middleware turns post deletes into updates of deletedAt. Upgrade to Prisma 7 and keep soft delete working.Illustrative; not a recorded model run. Generator switched to prisma-client with an output path; url removed from the datasource and set in prisma.config.ts; PrismaClient constructed with PrismaPg; imports from the generated output; $use replaced by a $extends extension adding post.softDelete and a findMany filter, with a note that findUnique and aggregates need explicit deletedAt filters; duplicate @@index on the @unique email removed; prisma validate, generate and tsc listed as checks.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/prisma-orm-best-practices.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Prisma ORM Best Practices: Prisma 7 Schema, Config, Queries and Extensions project conventions"
globs: "**/*"
alwaysApply: false
---
# Prisma ORM Best Practices
Applies to: `schema.prisma`, `prisma.config.ts`, migrations and Prisma Client queries in a TypeScript project.
Version baseline: checked against the Prisma ORM 7 documentation and upgrade guide. Read `package.json` first. If the project is still on Prisma 5 or 6, keep its existing generator and datasource style and follow the upgrade guide before adopting the Prisma 7 patterns below.
## Prisma 7 setup facts
- Use the `prisma-client` generator with an explicit `output`; the client is no longer generated into `node_modules`. `prisma-client-js` is deprecated.
- Connection URLs live in `prisma.config.ts`, not in the `datasource` block; Prisma 7 rejects `url = env(...)` in the schema.
- Prisma Client is created with a driver adapter (for PostgreSQL, `@prisma/adapter-pg`). Environment variables are not loaded automatically; load them (for example `import 'dotenv/config'`) where the config is read.
- The `$use` middleware API is removed. Use Client Extensions (`$extends`).
## Schema
```prisma
generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
}
datasource db {
provider = "postgresql"
}
model User {
id String @id @default(cuid())
email String @unique
name String?
role Role @default(USER)
posts Post[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@map("users")
}
model Post {
id String @id @default(cuid())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
authorId String
tags Tag[]
deletedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([authorId])
@@index([published, createdAt])
@@map("posts")
}
model Tag {
id String @id @default(cuid())
name String @unique
posts Post[]
@@map("tags")
}
enum Role {
USER
ADMIN
}
```
- `@unique` already creates an index; do not add a duplicate `@@index` on the same column.
- Index foreign keys used in filters and the column combinations used in `where` + `orderBy`. Confirm with `EXPLAIN` on real queries rather than indexing every column.
- Choose `onDelete` per relation deliberately (`Cascade`, `Restrict`, `SetNull`) and document why.
- Store password hashes only, in a field or table the API never selects by default.
```ts
// prisma.config.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') },
})
```
`env()` throws when the variable is unset, so every Prisma CLI command (including `generate` and `validate`) needs `DATABASE_URL` present, for example a placeholder value in CI jobs that only generate the client. If that is a problem, read `process.env.DATABASE_URL` instead and let commands that need a connection fail on their own.
## Client instance
Create one client per process and reuse it (in Next.js dev, cache it on `globalThis` to survive hot reload).
```ts
// src/lib/prisma.ts
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from '../generated/prisma/client'
export const prisma = new PrismaClient({
adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
})
```
## Query patterns
- Use `select` to return only needed fields (and never the password hash); use `include` only when you need the whole related records.
- Avoid N+1 loops: fetch relations with `include`/`select` or a single `findMany({ where: { id: { in: ids } } })`.
- Use the array form of `$transaction` for independent writes that must commit together, and the interactive form when later steps depend on earlier reads. Keep interactive transactions short and free of network calls.
```ts
// src/posts.ts
import { prisma } from './lib/prisma'
export async function publishFirstDraft(authorId: string) {
return prisma.$transaction(async (tx) => {
const draft = await tx.post.findFirst({
where: { authorId, published: false, deletedAt: null },
orderBy: { createdAt: 'asc' },
select: { id: true },
})
if (!draft) return null
return tx.post.update({ where: { id: draft.id }, data: { published: true } })
})
}
export async function listPosts(page: number, limit: number) {
const where = { published: true, deletedAt: null }
const [data, total] = await prisma.$transaction([
prisma.post.findMany({ where, skip: (page - 1) * limit, take: limit, orderBy: { createdAt: 'desc' } }),
prisma.post.count({ where }),
])
return { data, total, totalPages: Math.ceil(total / limit) }
}
export async function listPostsAfter(cursor: string | undefined, limit = 20) {
const rows = await prisma.post.findMany({
where: { published: true, deletedAt: null },
take: limit + 1,
...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
})
const hasMore = rows.length > limit
const data = hasMore ? rows.slice(0, limit) : rows
return { data, nextCursor: hasMore ? data[data.length - 1]?.id ?? null : null }
}
```
Prefer cursor pagination for large or frequently changing tables; order by a unique tie-breaker (`id`) so pages are stable.
## Soft delete with a Client Extension
Replace the removed `$use` middleware with a query extension, and keep the filter visible in reads:
```ts
// src/lib/soft-delete.ts
import { prisma } from './prisma'
export const db = prisma.$extends({
model: {
post: {
async softDelete(id: string) {
return prisma.post.update({ where: { id }, data: { deletedAt: new Date() } })
},
},
},
query: {
post: {
async findMany({ args, query }) {
args.where = { deletedAt: null, ...args.where }
return query(args)
},
},
},
})
```
Unique lookups (`findUnique`) and aggregates are not covered by this `findMany` hook; filter `deletedAt: null` explicitly there or extend those operations too.
## Migrations
- Change the schema, then `npx prisma migrate dev --name <change>` locally; commit the generated SQL.
- Deploy with `npx prisma migrate deploy`; never run `migrate dev` or `db push` against production.
- Review generated SQL for destructive steps (dropped columns, type changes) and split risky changes into expand/migrate/contract releases.
## Verify before finishing
- `npx prisma validate` and `npx prisma format` pass.
- `npx prisma generate` then `npx tsc --noEmit` pass (`validate` does not report a missing generator `output`; `generate` does).
- For schema changes, `npx prisma migrate dev` against a local or disposable database produces the expected SQL.
- Queries you added return only selected fields (check the TypeScript result type).
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.