Skip to content
BackendChapter 24 / 34Advanced5 min read

Database Integration

Next.js Prisma Drizzle database integration guide, covering the singleton client, queries in Server Components and mutations with Server Actions.

On this page

1. What is database integration?

An ORM (Object Relational Mapper) makes SQL tables feel like TypeScript objects. There are two popular choices with Next.js:

ORMWhat it is known for
PrismaA schema.prisma file, a generated typed client, a readable API like findMany
DrizzleThe schema in TypeScript, an SQL-like API, light and fast

Both work with PostgreSQL, MySQL and SQLite.

2. Why does it matter?

Thanks to Server Components, you no longer need a separate backend. A component can talk to the database directly. But if you create the connection the wrong way, you run out of connections during development.

A new client in every fileSingleton client
A new connection pool on every hot reloadOne client reused on globalThis
Too many connections errorConnections stay under control
Raw SQL strings, no typesTyped queries, autocomplete
Create an API route and fetch itQuery directly in a Server Component

3. Where is it used?

PlaceWhat the database does
Server ComponentReads data, with "use cache" or inside Suspense
Server ActionCreate, update, delete, then updateTag
Route HandlerQueries for a public API or a webhook
Data Access LayerAll queries in one place, with auth checks

Client Components never touch the database directly. They call a Server Action or receive data in props.

4. How does it work?

Request flow with a database
Request
Server Component or Server Action
A DAL function checks auth
The singleton ORM client runs the query
Database result
UI renders or the cache is invalidated

5. Code example

Example 1: Prisma singleton lib/db.ts

ts
import "server-only";
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "@/generated/prisma/client";

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

function createClient() {
  const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
  return new PrismaClient({ adapter });
}

export const db = globalForPrisma.prisma ?? createClient();

if (process.env.NODE_ENV !== "production") {
  globalForPrisma.prisma = db;
}

Example 2: the same idea with Drizzle

ts
import "server-only";
import { drizzle } from "drizzle-orm/node-postgres";
import { pgTable, serial, text, timestamp } from "drizzle-orm/pg-core";

export const posts = pgTable("posts", {
  id: serial("id").primaryKey(),
  title: text("title").notNull(),
  createdAt: timestamp("created_at").defaultNow().notNull(),
});

export const drizzleDb = drizzle(process.env.DATABASE_URL as string);

Example 3: reading and writing

tsx
import { cacheLife, cacheTag, updateTag } from "next/cache";
import { db } from "@/lib/db";

async function getPosts() {
  "use cache";
  cacheLife("hours");
  cacheTag("posts");
  return db.post.findMany({ select: { id: true, title: true }, take: 20 });
}

async function addPost(formData: FormData) {
  "use server";
  const title = String(formData.get("title") ?? "").trim();
  if (!title) return;
  await db.post.create({ data: { title } });
  updateTag("posts");
}

export default async function PostsPage() {
  const posts = await getPosts();

  return (
    <main>
      <form action={addPost}>
        <input name="title" placeholder="Post title" />
        <button type="submit">Add</button>
      </form>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </main>
  );
}

How does the code work?

PartMeaning
import "server-only"The build fails if it is imported into the client bundle by mistake
The client on globalThisA hot reload in dev does not create a new client
PrismaPg adapterPrisma 7 connects to the database through a driver adapter
drizzle(process.env.DATABASE_URL)The Drizzle client, with the schema in TypeScript
select: { id, title }Only the needed columns, so less data
"use cache" + cacheTagThe query result is cached, with a tag
updateTag("posts")The new post shows up in the list immediately

In a real app, addPost should also have an auth check, like verifySession() in the Authentication chapter.

Interview tip

"Why do you get a too many connections error in Next.js dev?" Answer: the module runs again on every hot reload and creates a new client. A globalThis singleton lets you reuse one client.

6. Common mistakes

Mistake: Creating a new PrismaClient in every file

Why? Each instance opens its own connection pool, and the database limit runs out quickly.

Better: Create a singleton in one lib/db.ts and import the same one everywhere.

Mistake: Importing the database client in a Client Component

Why? Secrets and Node only code try to go into the browser bundle, and the build breaks.

Better: Add server-only to the DB file and give data through a Server Component or a Server Action.

Mistake: Selecting the whole row and passing it to a Client Component

Why? A password hash or private columns can reach the browser.

Better: Take only the needed fields with select or columns.

Mistake: Fetching your own API route from a Server Component

Why? It is an extra HTTP hop, slow and needlessly complex.

Better: Call the DAL or an ORM function directly from the Server Component.

7. What to learn before and after

Final quick revision

PointDetail
ORMPrisma or Drizzle
ClientA singleton, on globalThis, with server-only
ReadingServer Component, "use cache" or Suspense
WritingA Server Action, then updateTag
SecurityAuth in the DAL, only the needed columns