# Next.js 15 + Prisma ORM + PostgreSQL — AI Agent Guidelines & Architecture Rules

> Production guidelines for Next.js App Router, Server Actions, Prisma connection pooling, PgBouncer/Neon tuning, and Zod schema validation.
> Technologies: Next.js, Prisma, PostgreSQL, TypeScript, Tailwind CSS

---

## AGENTS.md
```markdown
# Project Architecture & Guidelines (Next.js 15 + Prisma + PostgreSQL)

## 1. System Architecture
- **Framework**: Next.js 15 (App Router, Server Components by default).
- **Database & ORM**: PostgreSQL with Prisma ORM (`@prisma/client`, `prisma`).
- **Connection Pooling**: PgBouncer / Neon pooled connection string on port 6543 (`pgbouncer=true&connection_limit=1` for serverless Lambdas).
- **Validation & Types**: TypeScript (strict mode) + Zod for runtime schema validation.

## 2. Prisma Client & Connection Management (Critical)
- Always implement the global singleton pattern in `src/lib/prisma.ts` to prevent connection exhaustion during development HMR:
  ```typescript
  import { PrismaClient } from '@prisma/client';

  const globalForPrisma = globalThis as unknown as { prisma: PrismaClient | undefined };

  export const prisma =
    globalForPrisma.prisma ??
    new PrismaClient({
      log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
    });

  if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;
  ```
- Never call `$connect()` or `$disconnect()` manually inside Server Actions or route handlers.
- In production serverless environments, tune `connection_limit=1` or `connection_limit=2` in `DATABASE_URL`.
- Use `DIRECT_URL` (direct port 5432) for running migrations via `prisma migrate deploy`.

## 3. Server Actions & Mutations
- Place server mutations in `src/actions/` with `'use server'` directive.
- Parse and validate all inputs with Zod before executing Prisma queries.
- Return typed result objects: `{ success: true, data: T } | { success: false, error: string }`.
- Keep client components minimal; fetch data in React Server Components (RSC) and pass down as props.

## 4. Migration & Schema Workflow
- Schema source of truth: `prisma/schema.prisma`.
- Development: Run `bunx prisma migrate dev --name <migration_name>`.
- Production CI/CD: Run `bunx prisma migrate deploy`. NEVER use `db push` in production.
- Indexes: Explicitly define indexes (`@@index([userId, createdAt])`) for all foreign keys and frequently queried fields.

## 5. Common Pitfalls to Avoid
- ❌ Over-fetching: Avoid unconstrained `findMany()`; always pass `select` or `take` / `skip` pagination.
- ❌ N+1 Queries: Use Prisma `include` or batch queries instead of executing queries in loops.
- ❌ Exposing Database Secrets: Never prefix `DATABASE_URL` with `NEXT_PUBLIC_`.

## 6. Testing Conventions
- Use Vitest for unit tests on Server Actions; point the test Prisma client at a disposable schema or Docker Postgres instance, never a shared dev database.
- Use Playwright for e2e coverage of critical mutation flows (checkout, auth, billing) end-to-end through the real UI.
- Test Zod validation boundaries on every Server Action input schema — this is the first and cheapest layer to catch bad data.
- Run `bunx prisma validate` and `tsc --noEmit` in CI to catch schema/query drift before it reaches a migration.

## 7. Git Workflow & PR Conventions
- Conventional Commits (`feat:`, `fix:`, `refactor:`) scoped to the model or route, e.g. `fix(orders): prevent duplicate submission on double-click`.
- `prisma/migrations/` files ship in the same PR as the `schema.prisma` change that generated them — never hand-edit a generated migration.
- Require `tsc --noEmit` and `bun run build` green before merge.
- Never merge a PR containing `prisma db push` in its history against a shared environment; migrations only.
```

---

## CLAUDE.md
```markdown
# CLAUDE.md — Next.js + Prisma + PostgreSQL

Refer to @AGENTS.md for full architectural guidelines and connection rules.

## Essential Commands
- `bun run dev` - Start local Next.js development server
- `bun run build` - Typecheck and compile production bundle
- `bunx prisma migrate dev` - Generate & apply database migration
- `bunx prisma migrate deploy` - Apply pending migrations in production
- `bunx prisma studio` - Launch local database GUI viewer
- `bunx prisma generate` - Re-generate TypeScript Prisma client

## Claude Specific Directives
- When writing Server Actions, always validate inputs with Zod before calling `prisma.<model>.<action>()`.
- Adhere strictly to the singleton pattern in `src/lib/prisma.ts`.
```

---

## .cursor/rules/stack.mdc
```markdown
---
description: Next.js 15 + Prisma ORM + PostgreSQL architecture rules
globs: ["**/*.ts", "**/*.tsx", "prisma/**/*"]
alwaysApply: true
---

# Next.js 15 + Prisma ORM + PostgreSQL

- Next.js App Router, Server Components by default, Prisma over pooled Postgres (PgBouncer/Neon, port 6543).
- Global singleton `PrismaClient` in `src/lib/prisma.ts` via `globalThis` — never call `$connect()`/`$disconnect()` manually.
- `connection_limit=1` or `2` in `DATABASE_URL` for serverless; `DIRECT_URL` (port 5432) for `prisma migrate deploy`.
- Server mutations in `src/actions/` with `'use server'`; validate with Zod before any Prisma call.
- Return typed results: `{ success: true, data: T } | { success: false, error: string }`.
- `prisma migrate dev` locally, `prisma migrate deploy` in CI/CD — never `db push` in production.
- Explicit `@@index([...])` on every foreign key and frequently queried column.
- Never prefix `DATABASE_URL` with `NEXT_PUBLIC_`; paginate every `findMany()` with `take`/`skip` or a cursor.
```

---

## Architecture Overview & Best Practices
## Architecture Overview

Production conventions for building high-scale full-stack applications with **Next.js 15 App Router**, **Prisma ORM**, and **PostgreSQL**.

### Verified Real-World Adoption

This exact architecture is deployed in production by top open-source platforms including **Cal.com**, **Documenso**, **Papermark**, **Typebot**, **Formbricks**, and **Umami**.

### Key Architectural Nuances

- **Serverless Connection Management**: Using `globalThis` singleton client prevents Lambda / HMR connection pool leakage.
- **Migration Isolation**: Separating `DATABASE_URL` (pooled port 6543) from `DIRECT_URL` (migration port 5432) ensures atomic DDL schema updates.