Lesson 15 of 27Full-stack
Databases and the Data Access Layer
Connect Next.js to Postgres without exhausting connections, route every query through a server-only Data Access Layer, and return safe DTOs.
Your team's invoicing app works on your laptop. Then launch day arrives, traffic spikes, and the logs fill with sorry, too many clients already. A week later a security review finds that the invoice page sends every column of the customer row, including an internal credit score, to the browser inside the RSC payload. Neither bug is about SQL. Both are about where database code lives in a Next.js app and how it reaches Postgres. This lesson covers the choices a team makes once and lives with for years: the ORM, migrations, connection pooling, a Data Access Layer, DTOs, transactions and pagination.
A request, from button to row
Before the details, hold the whole path in your head. In the App Router, the database is only ever touched on the server, but "the server" is several different entry points: Server Components, Server Actions and Route Handlers. A good architecture funnels all of them through one layer.
Three server entry points. Each one is reachable from the internet, so each one must be treated as untrusted input.
Keep this picture. Every section below is one box in it.
Drizzle or Prisma
Most TypeScript teams in 2026 pick one of two ORMs. Both are good. The difference is philosophy.
| Drizzle | Prisma | |
|---|---|---|
| Schema | TypeScript files (pgTable(...)) | Its own schema.prisma language |
| Queries | SQL-shaped builder, plus a relational query API | Object API (findMany({ where, include })) |
| Output | Thin; you can predict the SQL from the code | More abstracted; you read logs to see the SQL |
| Migrations | drizzle-kit generate writes SQL files you commit | prisma migrate dev writes SQL files you commit |
| Feel | "SQL with types" | "A data model with a client" |
Pick Drizzle if your team knows SQL and wants to see exactly what runs. Pick Prisma if you value its schema language, Studio and a gentler API for people newer to SQL. Prisma 7 removed the old Rust query engine, so the client is plain TypeScript and connects through a driver adapter; that answered most of the historic complaints about bundle size and cold starts on serverless. Check each project's docs for the current setup steps, because both move fast.
Whichever you choose, the schema is code, reviewed like code:
import { pgTable, uuid, text, integer, timestamp, index } from "drizzle-orm/pg-core";
export const invoices = pgTable(
"invoices",
{
id: uuid("id").primaryKey().defaultRandom(),
teamId: uuid("team_id").notNull(),
customerName: text("customer_name").notNull(),
totalCents: integer("total_cents").notNull(),
paidCents: integer("paid_cents").notNull().default(0),
internalNotes: text("internal_notes"), // must never reach the browser
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("invoices_team_created_idx").on(t.teamId, t.createdAt, t.id)],
);Money is stored as integer cents, timestamps carry a time zone, and the index matches the query the list page runs (by team, newest first). The internalNotes column is a reminder that tables always hold more than any one screen should see.
Migrations run in CI, not at startup
A migration is a SQL file that moves the schema from one version to the next. The workflow that holds up in a team:
- Change the schema file and generate a migration locally (
drizzle-kit generateorprisma migrate dev). - Read the generated SQL in the pull request. Generators sometimes produce a drop-and-recreate where you wanted a rename.
- In CI, after tests pass, run the migration against production as its own step (
drizzle-kit migrateorprisma migrate deploy). - Only then does the new code go live.
Never run migrations when the app boots. On serverless you might have fifty instances starting at once, all racing to alter the same table.
Because old code keeps serving traffic for a while during a deploy, a migration must work with both the old and the new code. Renaming a column in one step breaks the old instances. The safe pattern is expand and contract: add the new column, deploy code that writes both, backfill, deploy code that reads only the new one, and drop the old column in a later release.
Put a safe column rename (from name to display_name) in order across several deploys.
- Tap the steps below in the right order.
Connections on serverless
A Postgres connection is a whole backend process on the database server, so Postgres caps them (often around 100 on small managed plans). A traditional Node server opens a pool of, say, 10 connections once and reuses them forever. Serverless and autoscaled containers break that assumption: each instance opens its own pool, and a traffic spike creates many instances. You saw the arithmetic in Deploying Next.js. The fixes, from most to least common:
- A pooled connection string. Neon, Supabase (Supavisor) and most managed hosts give you a second URL that goes through a pooler such as PgBouncer. In transaction mode the pooler lends a real connection only for the length of one transaction, so thousands of clients can share a few dozen connections.
- An HTTP or WebSocket driver. Neon's serverless driver sends each query over HTTP, so there is no long-lived connection to exhaust. It is fast for single queries, but the plain HTTP mode cannot hold an interactive transaction open across several round trips; use its WebSocket
Poolwhen you need one. - Platform pool helpers. Platforms that reuse function instances across requests have helpers that keep a pool alive and close idle connections before an instance is suspended. Check your host's docs.
The trap that bites seniors: transaction-mode pooling and prepared statements do not mix by default, because the next query may land on a different real connection that never saw the PREPARE. Many drivers need a flag for this, for example postgres(url, { prepare: false }) with postgres.js. If you see random prepared statement does not exist errors in production only, this is why.
import "server-only";
import postgres from "postgres";
import { drizzle } from "drizzle-orm/postgres-js";
import * as schema from "./schema";
// In dev, Fast Refresh re-runs this module on every edit. Without the cache
// on globalThis you would open a new pool each time and leak connections.
const globalForDb = globalThis as unknown as { pg?: ReturnType<typeof postgres> };
const client =
globalForDb.pg ??
postgres(process.env.DATABASE_URL!, {
max: 5, // small: many instances will each have a pool
prepare: false, // required behind a transaction-mode pooler
});
if (process.env.NODE_ENV !== "production") globalForDb.pg = client;
export const db = drizzle(client, { schema });The globalThis trick fixes a development-only leak. In production each module is evaluated once per instance, so it does nothing there, which is fine.
prepared statement s1 does not exist a few times an hour. Local development is fine. What is the most likely cause?The Data Access Layer
You met the DAL in Auth and Proxy as the place where authorization lives. Here is the full shape. It is a folder of server-only modules, and it is the only code that imports db. Each exported function does three things in order: find out who is asking, run a query scoped to what they may see, and return a DTO (data transfer object), a plain object containing only the fields the caller needs.
import "server-only";
import { and, eq } from "drizzle-orm";
import { db } from "@/db";
import { invoices } from "@/db/schema";
import { verifySession } from "@/data/auth";
export type InvoiceDTO = { id: string; customerName: string; total: string; createdAt: string };
function toInvoiceDTO(row: typeof invoices.$inferSelect): InvoiceDTO {
return {
id: row.id,
customerName: row.customerName,
total: (row.totalCents / 100).toFixed(2),
createdAt: row.createdAt.toISOString(),
};
}
export async function getInvoice(id: string): Promise<InvoiceDTO | null> {
const { teamId } = await verifySession();
const row = await db.query.invoices.findFirst({
where: and(eq(invoices.id, id), eq(invoices.teamId, teamId)), // scope in the query itself
});
return row ? toInvoiceDTO(row) : null;
}Notice the authorization is in the WHERE clause. Fetching by id and then comparing teamId in JavaScript also works, but putting the scope in SQL means a forgotten if cannot leak a row, and the database can use the index.
Why centralize? Because audits become a search. If db is imported only under data/, a reviewer can check every query in one folder. A lint rule (no-restricted-imports on @/db outside data/) turns the convention into a guarantee. Only the DAL should read database secrets from process.env, too.
DTOs: what crosses the wire
When a Server Component passes a prop to a Client Component, React serializes that prop into the RSC payload, a stream of data embedded in the HTML and fetched on navigation. Anyone can read it in the network tab. Rendering only invoice.customerName in the JSX does not help: if you passed the whole row, the whole row was sent.
Press Run (⌘ Enter) to see what happens.Write DTOs as an explicit list of fields you include, never as "the row minus some fields". A spread with a delete (const { internalNotes, ...rest } = row) silently starts leaking the next sensitive column someone adds to the table.
What does this print?
const row = { id: "u1", email: "a@x.io", passwordHash: "$argon2..." };
const { passwordHash, ...safe } = row;
// a month later, a migration adds a column:
const row2 = { ...row, resetToken: "tok_8f2" };
const { passwordHash: _, ...safe2 } = row2;
console.log(Object.keys(safe2).join(","));Writes: transactions and idempotency in Server Actions
A Server Action that changes more than one row needs a transaction: either every statement commits or none does. Keep the action thin and put the transaction in the DAL, next to the authorization check.
import "server-only";
import { and, eq, sql } from "drizzle-orm";
import { db } from "@/db";
import { invoices, payments } from "@/db/schema";
import { verifySession } from "@/data/auth";
export async function recordPayment(invoiceId: string, amountCents: number, idempotencyKey: string) {
const { teamId, userId } = await verifySession();
return db.transaction(async (tx) => {
const [invoice] = await tx
.select().from(invoices)
.where(and(eq(invoices.id, invoiceId), eq(invoices.teamId, teamId)))
.for("update"); // lock the row so two payments cannot race
if (!invoice) return { error: "Not found" as const };
const inserted = await tx
.insert(payments)
.values({ invoiceId, amountCents, createdBy: userId, idempotencyKey })
.onConflictDoNothing({ target: payments.idempotencyKey })
.returning({ id: payments.id });
if (inserted.length === 0) return { ok: true as const, duplicate: true }; // already recorded
await tx.update(invoices)
.set({ paidCents: sql`${invoices.paidCents} + ${amountCents}` })
.where(eq(invoices.id, invoiceId));
return { ok: true as const, duplicate: false };
});
}Two production details hide in there.
Idempotency. Users double-click, networks retry, and a phone on a train resends the POST. The form includes a hidden key generated once when the form renders (for example crypto.randomUUID()), and a unique constraint on idempotency_key makes the second insert a no-op. The database enforces "at most once", not your JavaScript, so it holds even when two requests arrive on two different instances at the same moment.
Keep transactions short. A transaction holds a pooled connection and row locks until it ends. Never call a payment provider, send an email or fetch anything slow inside one. Do the external call first (with its own idempotency key), or after commit. Also call redirect() and updateTag() after the DAL returns, outside the transaction, since redirect throws.
The user clicks Pay. The form carries key k1, created when the form rendered.
Pagination with searchParams
List pages read the page position from the URL, so it is shareable and survives refresh. There are two ways to page.
Offset (?page=3 becomes LIMIT 20 OFFSET 40) is simple and lets users jump to page 7. But the database still reads and throws away the skipped rows, so deep pages get slow, and if new rows arrive between requests, everything shifts and the user sees duplicates or misses rows.
Cursor (also called keyset) pagination remembers the last row seen (?after=2026-10-01T09:00:00Z_inv_17) and asks for rows that sort after it: WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT 21. It uses the index directly, stays fast at any depth, and is stable under inserts. You lose "jump to page 7", which feeds and infinite scroll do not need anyway. Including id as a tie-breaker matters: timestamps are not unique.
Watch offset paging break when a row is inserted between page loads:
Press Run (⌘ Enter) to see what happens.In the page, validate the cursor before it reaches the query. It is user input like any other search param: parse it with Zod, and fall back to the first page if it is malformed instead of throwing a 500.
Match each problem to the tool that solves it.
Caching database reads
With Cache Components, a DAL function can be cached with "use cache" and tagged with cacheTag, as you saw in Data Fetching and Caching. There is one rule that trips people up: a cached function cannot read cookies() or headers(), because a cache entry is shared. So split the function. Do the session check outside, then call a cached inner function that takes the scope as an argument.
import { cacheTag, cacheLife } from "next/cache";
async function listInvoicesForTeam(teamId: string, after?: string) {
"use cache";
cacheTag(`invoices:${teamId}`);
cacheLife("minutes");
// ...query scoped by teamId, return DTOs (cached values must be serializable)
}
export async function listInvoices(after?: string) {
const { teamId } = await verifySession(); // auth is never cached
return listInvoicesForTeam(teamId, after);
}The arguments become part of the cache key, so each team gets its own entry. After recordPayment, the action calls updateTag(`invoices:${teamId}`) so the next read is fresh. Never cache the function that checks the session.
What about Row-Level Security?
Postgres can enforce tenancy itself with Row-Level Security (RLS): a policy like USING (team_id = current_setting('app.team_id')::uuid) filters every query on the table. Supabase leans on RLS heavily because its client can talk to the database from the browser. In a Next.js app where only the server talks to the database, the DAL usually does this job, but some teams add RLS as a second layer so that a forgotten WHERE in a hand-written query still cannot cross tenants. If you do, set the setting with SET LOCAL inside each transaction, because a pooled connection is shared with other users' requests.
- Data Access Layer (DAL)
- A set of
server-onlymodules that is the only code allowed to query the database; it checks auth, scopes the query and returns DTOs. - DTO
- A data transfer object: a plain object with only the fields a caller needs, built from an explicit allow-list.
- connection pooler
- A proxy such as PgBouncer or Supavisor that lets many clients share a small number of real Postgres connections.
- transaction mode
- A pooling mode where a real connection is lent for one transaction at a time; it breaks session state such as prepared statements.
- expand and contract
- Changing a schema in backward-compatible steps across several deploys, so old and new code both work at every point.
- idempotency key
- A unique value sent with a request so that repeating it has no extra effect; enforced with a unique constraint.
- cursor pagination
- Paging by the last row seen (
WHERE (created_at, id) < cursor) instead ofOFFSET; fast at any depth and stable under inserts.