Skip to main content
⚡ OpenDevDocs
Next.js
fullstacknextjsRecipeIntermediate

Next.js + PostgreSQL + Prisma ORM

Complete step-by-step setup connecting Next.js App Router to a PostgreSQL database with Prisma ORM and singleton client connection management.

Verified: 2026-09-30
Tested on:nextjs 16.x, prisma 6.x, postgres 16.x
Platforms:
all
#nextjs#postgresql#prisma#orm#database

Goal

Configure a production-ready PostgreSQL connection inside Next.js App Router using Prisma ORM, supporting local schema migrations, TypeScript autocompletion, and safe singleton client reuse across server actions and route handlers.


Prerequisites

  • Node.js 20+ or 22+ installed
  • A running PostgreSQL database instance (local Docker, Supabase, Neon, or RDS)
  • An existing Next.js App Router project

Architecture Overview

[ Next.js Server Components / Actions ]
               │
               ▼
   [ lib/prisma.ts Singleton ]
               │
               ▼ (Connection Pool)
     [ PostgreSQL Database ]

<PackageManagerTabs package="@prisma/client" />
<PackageManagerTabs package="prisma" dev />
<Command>pnpm prisma init --datasource-provider postgresql</Command>
```ini
DATABASE_URL="postgresql://postgres:yourpassword@localhost:5432/my_app_db?schema=public"
```
```prisma
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id        String   @id @default(cuid())
  email     String   @unique
  name      String?
  createdAt DateTime @default(now())
  posts     Post[]
}

model Post {
  id        String   @id @default(cuid())
  title     String
  content   String?
  published Boolean  @default(false)
  authorId  String
  author    User     @relation(fields: [authorId], references: [id], onDelete: Cascade)
  createdAt DateTime @default(now())
}
```
<Command>pnpm prisma migrate dev --name init</Command>
```typescript
// lib/prisma.ts
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;
}
```
```tsx
// app/users/page.tsx
import { prisma } from "@/lib/prisma";

export default async function UsersPage() {
  const users = await prisma.user.findMany({
    orderBy: { createdAt: "desc" },
    include: { posts: true },
  });

  return (
    <main className="p-8">
      <h1 className="text-2xl font-bold mb-4">Users Directory</h1>
      <ul className="space-y-2">
        {users.map((user) => (
          <li key={user.id} className="p-3 rounded border">
            <span className="font-semibold">{user.name ?? "Anonymous"}</span> — {user.email}
            <span className="text-xs text-muted-foreground ml-2">({user.posts.length} posts)</span>
          </li>
        ))}
      </ul>
    </main>
  );
}
```

Verification

Run the dev server and inspect database queries in the terminal:

pnpm dev

Open http://localhost:3000/users to verify records render with zero connection warnings.


Security & Production Considerations

  1. Connection Pooling in Serverless: If deploying to Vercel or AWS Lambda, use a transaction-level connection pooler like PgBouncer or Neon / Supabase Connection Pooler with ?pgbouncer=true&connection_limit=1.
  2. Never Expose Client in Browser: Keep lib/prisma.ts exclusively imported in Server Components, Server Actions, or Route Handlers.
  3. Database URL Secret: Add .env and .env.local to .gitignore. Never commit database credentials.

On this page