Next.js and Databases: Prisma, Drizzle, and Pooling
Server Components turn a Next.js page into a place where database queries belong. There is no API hop, no serialization boundary, and no client-side loading state for data the user cannot act on anyway. That convenience hides three operational problems that bite every project sooner or later: the ORM client gets recreated on every hot-reload and exhausts the connection pool, serverless functions open far more connections than the database can serve, and migrations drift out of sync with the code that queries them.
This lesson walks through choosing an ORM, wiring a resilient client singleton, querying from Server Components and Server Actions, and configuring pooling so a production deploy does not collapse under its own connection churn.
Prerequisites
- !Working knowledge of async Server Components
- !A Postgres, MySQL, or SQLite database you can access
- !Comfort with environment variables and npm scripts
What You'll Learn
- 1Compare Prisma and Drizzle on the dimensions that matter for Next.js apps
- 2Create a dev-safe database client singleton
- 3Query and mutate data from pages, layouts, and Server Actions
- 4Choose between direct connections and a pooled or accelerated driver
Choosing between Prisma and Drizzle
Both ORMs generate type-safe queries, but they optimize for different workflows. Prisma ships a schema file, a migration engine, and a query client whose API reads like the database it sits on. Drizzle leans on TypeScript itself as the schema language, produces SQL that closely mirrors what you write, and stays out of the way at runtime. Either is a good choice; the deciding factors are usually migration ergonomics and how much SQL your team wants to see.
| Dimension | Prisma | Drizzle |
|---|---|---|
| Schema definition | Dedicated .prisma schema file | TypeScript table definitions |
| Query style | Nested, relation-aware client | SQL-shaped, composable builders |
| Migrations | prisma migrate, built-in engine | drizzle-kit push and generate |
| Bundle weight | Larger runtime, CLI-heavy tooling | Small runtime, tree-shakeable |
| Learning curve | Gentle for CRUD, deeper for advanced queries | Steeper if SQL is unfamiliar, thinner overall |
| Best fit | Apps that want batteries included | Apps that want SQL transparency |
For a fast product with heavy relational reads, Prisma's include and nested writes save real code. For an analytics-heavy service where every query is tuned, Drizzle's SQL-shaped API and zero-idiomatic-runtime tend to win.
A client singleton that survives hot reload
In development, every file change can re-instantiate module state. Creating a PrismaClient at module scope without a global guard multiplies connections until the database refuses new ones. The standard fix stashes the instance on globalThis only in non-production builds.
// lib/db.js
import { PrismaClient } from '@prisma/client';
const globalForPrisma = globalThis;
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: ['warn', 'error'],
});
if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = prisma;
}
Drizzle needs the same pattern with drizzle-orm's postgres or node-postgres driver. The rule is identical: one process, one pool, survive the dev server's module churn without leaking sockets.
Querying from Server Components
A page that reads data on the server ships no fetch logic to the browser and renders its real content in the initial HTML response. Keep queries near the route that needs them, select only the columns you render, and let layouts share expensive reads through request memoization.
// app/orders/page.js
import { prisma } from '@/lib/db';
export const dynamic = 'force-dynamic';
export default async function OrdersPage({ searchParams }) {
const { status } = await searchParams;
const orders = await prisma.order.findMany({
where: status ? { status } : {},
include: { customer: { select: { name: true, email: true } } },
orderBy: { createdAt: 'desc' },
take: 50,
});
return (
<main>
<h1>Recent orders</h1>
<table>
<thead>
<tr><th>Customer</th><th>Status</th><th>Total</th></tr>
</thead>
<tbody>
{orders.map((order) => (
<tr key={order.id}>
<td>{order.customer.name}</td>
<td>{order.status}</td>
<td>{order.total}</td>
</tr>
))}
</tbody>
</table>
</main>
);
}
Notice the explicit force-dynamic: reading searchParams already makes the route dynamic, but declaring the intent keeps the build output honest and prevents a future refactor from accidentally caching personalized order data at the CDN.
Mutations belong in Server Actions
Server Actions keep the write path on the server without standing up a REST route. Validate the input, perform the write, then revalidate the affected paths so the Full Route Cache reflects the new row.
// app/orders/actions.js
'use server';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { prisma } from '@/lib/db';
export async function createOrder(prevState, formData) {
const customerId = formData.get('customerId');
const total = Number(formData.get('total'));
if (!customerId || Number.isNaN(total) || total <= 0) {
return { error: 'Valid customer and positive total are required' };
}
const order = await prisma.order.create({
data: { customerId, total, status: 'pending' },
});
revalidatePath('/orders');
redirect(`/orders/${order.id}`);
}
Returning a plain object for recoverable errors and redirecting only on success keeps useActionState wiring simple: the form stays mounted with its values, the error message renders inline, and navigation happens only after the write commits.
Relations, includes, and the N+1 trap
Relational data is where ORMs earn their reputation, and where they quietly produce N+1 query patterns that only appear under production load. Rendering an order list that includes the customer name looks like one call to prisma.order.findMany with include: customer, and Prisma executes a efficient two-query join under the hood. The same list rendered through a hand-written loop that queries the customer for each order issues one extra query per row â fifty rows, fifty round trips. The two patterns look similar in code review and differ by an order of magnitude in latency.
Both Prisma and Drizzle give you tools to see what is actually happening. Prisma's log option can emit query events, and a single request through a page with the log enabled will show whether the database received one query or fifty-one. Drizzle's SQL-shaped API makes the join explicit in the builder, which makes accidental per-row loops harder to write but also requires you to think in set-based terms from the start. The underlying rule is the same for both: a list view should never scale its query count with the number of rows it renders.
Deep relations raise a second concern: over-fetching. include with nested selects can pull an entire object graph â orders including customers including addresses including geocode rows â when the template only renders a name and a city. Use select inside include to project exactly the fields the page displays. The bandwidth saving at the database, the serialization cost at the framework, and the payload size in the HTML all shrink together, and the query planner works with smaller intermediate results.
Connection pooling on serverless platforms
A deployed Next.js app on a serverless platform can run dozens of function instances at once. Each instance holding its own direct Postgres connection multiplies beyond what the database's max_connections allows, and the first symptom is intermittent connection timeouts under load. Two fixes dominate: use a pooled connection string that routes through a transaction pooler such as PgBouncer, or use a driver built for the serverless model, such as Prisma's Accelerate or the HTTP-based Neon driver.
// lib/db-pooled.js
import { PrismaClient } from '@prisma/client';
const globalForPrisma = globalThis;
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
datasources: {
db: {
// pooled string from your provider's dashboard
url: process.env.DATABASE_POOLED_URL,
},
},
});
if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = prisma;
}
Keep two variables in your environment: a direct URL for migrations run from your machine or CI, and a pooled URL for the application runtime. Drizzle users make the same split by instantiating the driver with the pooled connection string in production.
Migrations that stay in sync
Schema changes should ship as reviewable SQL files, never as ad-hoc console edits. Prisma records migrations in prisma/migrations and applies pending ones with prisma migrate deploy during the release step; Drizzle stores generated SQL in a similar folder and applies it with drizzle-kit. Whichever tool you pick, run the migration step before the new code goes live whenever a change is additive, and write backwards-compatible code when a change removes a column or tightens a constraint, so old and new revisions overlap safely during a rolling deploy.
Two migration patterns deserve special care. Adding a NOT NULL column to a table with existing rows fails instantly on any database; the safe sequence is to add the column nullable, backfill it in batches, then tighten the constraint once the backfill completes. Renaming a column has the same problem in reverse: old code still references the old name until every instance of the application has rolled forward. Treat multi-step migrations as deploy units of their own, each paired with code that tolerates both the before and after states of the schema. This discipline is more effort than an ad-hoc ALTER, and it is the difference between a routine release and a five-minute outage that pages the on-call engineer.
Common Mistakes
Instantiating the ORM client at module scope without a global guard
Fix: Store the instance on globalThis in development so hot reload does not exhaust the connection pool.
Selecting entire rows with findMany and no select clause
Fix: Project only the columns the page renders; it reduces payload size and prevents accidental exposure of sensitive fields.
Running migrations with the same pooled URL the app uses
Fix: Migrations need a direct connection; keep DATABASE_URL for migrations and DATABASE_POOLED_URL for the runtime.
Leaving force-dynamic on routes after debugging is finished
Fix: Check the build output route table regularly and restore caching wherever the data allows it.
Best Practices
- Centralize the client in one lib/db module so every import shares a single pool
- Use transactions for multi-step writes; Server Actions can await prisma.$transaction directly
- Select explicitly on every query to keep payloads minimal and permissions tight
- Add a read replica or cache layer only after measuring that the database is the bottleneck
Interview Questions
Q1: Why does my dev server crash with too many connections after a few minutes?
Each hot reload creates a fresh PrismaClient without closing the old pool. A globalThis singleton keeps one instance per process.
Q2: Direct URL or pooled URL â which belongs in the app runtime?
The pooled URL. Serverless instances multiply connections; a transaction pooler multiplexes them so the database sees a bounded number.
Q3: Where should a mutation's revalidation live?
Inside the Server Action after the write commits: call revalidatePath for list and detail routes, then redirect when the user should navigate.
Key Takeaways
- Server Components can query the database directly, but personalization must force the route dynamic.
- Guard your ORM client with a globalThis singleton to survive dev hot reload.
- Split direct and pooled connection strings; migrations take the direct path, the runtime takes the pooled one.
- Prisma favors batteries-included CRUD; Drizzle favors SQL transparency â both are production-grade.
- Ship schema changes as reviewed migrations applied before or safely alongside the code that depends on them.