Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 72 ยท Data Fetching and Caching

Databases in Next.js - MongoDB, Prisma and Drizzle

Connect a Next.js app to MongoDB, Prisma or Drizzle. Reuse one connection in development, query from Server Components and Route Handlers, and keep secrets on the server.

Nearly every real app stores something. In the App Router you do not need a separate API server to reach a database: a Server Component or a Server Action is already code that runs on the server, so it can talk to the database directly. That is convenient, but it comes with two jobs that are easy to get wrong. You must reuse one connection instead of opening a new one on every reload, and you must keep the credentials and the raw query code away from the browser.

This lesson covers the connection pattern that works for any database, then shows how it looks with the MongoDB driver (and Mongoose), with Prisma and with Drizzle. A database server cannot run on this site, and neither can Next.js, so the real code is in read-only blocks. The runnable examples are Node.js stand-ins: one shows why development needs a global singleton, and one is a small in-memory document store with Mongo-style filters, so you can see what the query code does.

Prisma, Drizzle and Mongoose are third-party libraries with their own versions and documentation. The patterns below are stable, but check the current docs for exact option names before you install anything. Data-layer structure (a data/ folder, a data access layer) is covered in Data Access Patterns.

Three common choices

MongoDB driver Documents. Flexible shapes.
Prisma Schema file and a generated client.
Drizzle Typed SQL written in TypeScript.

All three work the same way in Next.js.

1 / 2

Where database code may run

Database code belongs in places that only run on the server:

  • Server Components can await a query and render the result. Nothing of the query is sent to the browser except the HTML or RSC payload.
  • Server Actions run mutations: insert, update and delete after a form post.
  • Route Handlers (route.ts) expose JSON for mobile apps or other clients.
  • Never a Client Component. A "use client" file is bundled for the browser, so a connection string in it would be public.

Protect your data module with the server-only package, as shown in Keeping Server Code on the Server. Importing it from a Client Component then fails the build instead of leaking a secret. Keep the connection string in .env.local as a variable without the NEXT_PUBLIC_ prefix (see Environment Variables).

The connection problem in development

In production a server process starts once, loads each module once and keeps the connection for its whole life. In development it is different: when you save a file, Next.js re-evaluates changed modules (hot reload). If a module that creates a database client is evaluated again, it creates a second client, then a third. Every client holds several open connections, so after an hour of editing the database refuses new ones with an error about too many connections.

The fix is to keep the client on globalThis, which survives hot reloads, and create a client only when there is none. The stand-in imitates a module being evaluated again and again, with and without the guard.

Node.js Why development needs a global singleton

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The same idea works for every library. You will see it again below.

MongoDB

MongoDB stores JSON-like documents in collections. The official mongodb driver returns a MongoClient. It manages its own pool of connections, so you create one client and share it.

TypeScript
// lib/mongodb.ts (read-only)
import "server-only";
import { MongoClient } from "mongodb";

const uri = process.env.MONGODB_URI;
if (!uri) throw new Error("MONGODB_URI is not set");

const globalForMongo = globalThis as unknown as { mongoClient?: Promise<MongoClient> };

export const clientPromise: Promise<MongoClient> =
  (globalForMongo.mongoClient ??= new MongoClient(uri).connect());

The module stores a promise of a connected client, so two requests that arrive while the connection is still opening share the same attempt. Use it in a Server Component:

TSX
// app/notes/page.tsx (read-only)
import { clientPromise } from "@/lib/mongodb";

type Note = { _id: string; title: string; done: boolean };

export default async function NotesPage() {
  const client = await clientPromise;
  const notes = await client
    .db("app")
    .collection<Note>("notes")
    .find({ done: false })
    .sort({ _id: -1 })
    .limit(20)
    .toArray();

  return (
    <ul>
      {notes.map((note) => (
        <li key={String(note._id)}>{note.title}</li>
      ))}
    </ul>
  );
}

One detail: a MongoDB _id is an ObjectId, a class instance. A Server Component may render it as text, but you cannot pass it as a prop to a Client Component (props must be serializable, see Server and Client Composition). Convert with String(note._id) or map the documents to plain objects first.

Mongoose adds schemas and models on top of the driver. Its connection also needs caching, and its model registration must not run twice on hot reload:

TypeScript
// models/note.ts (read-only)
import mongoose, { Schema, models, model } from "mongoose";

const noteSchema = new Schema({ title: { type: String, required: true }, done: { type: Boolean, default: false } });

export const Note = models.Note || model("Note", noteSchema);

The models.Note || guard is the same hot-reload fix as before: define the model only if it does not exist yet.

Node.js A tiny document store with Mongo-style filters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Prisma

Prisma starts from a schema file that describes your tables. A command generates a typed client from it, so prisma.user.findMany() is checked by TypeScript against your real columns.

PRISMA
// prisma/schema.prisma (read-only)
model Post {
  id        Int      @id @default(autoincrement())
  title     String
  published Boolean  @default(false)
  createdAt DateTime @default(now())
}
TypeScript
// lib/prisma.ts (read-only)
import "server-only";
import { PrismaClient } from "@prisma/client";

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

export const prisma = globalForPrisma.prisma ?? new PrismaClient();

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

This is the global singleton again. In production the guard is not needed, because the module is evaluated once. Using it:

TSX
// app/posts/page.tsx (read-only)
import { prisma } from "@/lib/prisma";

export default async function PostsPage() {
  const posts = await prisma.post.findMany({
    where: { published: true },
    orderBy: { createdAt: "desc" },
    take: 10,
  });
  return <ul>{posts.map((post) => <li key={post.id}>{post.title}</li>)}</ul>;
}

You change the schema, then run prisma migrate dev to create a migration and prisma generate to refresh the client. Check the Prisma documentation for the current client setup, because the generated client location and configuration have changed between major versions.

Drizzle

Drizzle describes tables in TypeScript and writes queries that look like SQL. There is no code generation step: the types come from your table definitions.

TypeScript
// db/schema.ts (read-only)
import { pgTable, serial, text, boolean } from "drizzle-orm/pg-core";

export const posts = pgTable("posts", {
  id: serial("id").primaryKey(),
  title: text("title").notNull(),
  published: boolean("published").notNull().default(false),
});
TypeScript
// db/index.ts (read-only)
import "server-only";
import { drizzle } from "drizzle-orm/node-postgres";
import { Pool } from "pg";

const globalForDb = globalThis as unknown as { pool?: Pool };
const pool = (globalForDb.pool ??= new Pool({ connectionString: process.env.DATABASE_URL }));

export const db = drizzle(pool);
TSX
// app/posts/page.tsx (read-only)
import { eq, desc } from "drizzle-orm";
import { db } from "@/db";
import { posts } from "@/db/schema";

export default async function PostsPage() {
  const rows = await db.select().from(posts).where(eq(posts.published, true)).orderBy(desc(posts.id)).limit(10);
  return <ul>{rows.map((row) => <li key={row.id}>{row.title}</li>)}</ul>;
}

Both Prisma and Drizzle send parameterized queries, so a value such as '; DROP TABLE posts; -- is treated as data, never as SQL. If you ever write raw SQL, use the library's tagged-template or placeholder form and never build a query string with + or template literals.

Serverless and connection limits

On serverless hosts every request may start a fresh function instance, and many instances can run at once, each with its own connections. A database that allows 100 connections can be exhausted by 100 concurrent instances. Common remedies are a connection pooler (the database provider's pooled connection string), an HTTP-based driver designed for serverless, or a small pool size (max: 1 or 2 per instance). Read your provider's guidance, and check that every instance closes idle connections.

Caching and revalidation

A database query is not a fetch() call, so Next.js does not cache it automatically. Opt in with "use cache" (see use cache and Cache Components) or use unstable_cache in older setups, and call revalidateTag or revalidatePath after a mutation (see Revalidation). Whatever you choose, read the cookie or session outside the cached function and pass the user id in as an argument, so one user's data is never cached for another.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do database modules in Next.js often store the client on globalThis?

    globalThis survives module re-evaluation, so the guard creates the client only once per process and avoids exhausting the database's connection limit.
  2. 2. Where must database queries and the connection string live?

    Anything in a Client Component is shipped to the browser. Keep queries on the server and secrets in variables without the NEXT_PUBLIC_ prefix.
  3. 3. A MongoDB document is rendered by a Server Component, but passing it to a Client Component fails. What is the likely cause?

    Props crossing the server-client boundary must be serializable. Convert the ObjectId with String() or map documents to plain objects.
  4. 4. Are database queries cached automatically like fetch() requests?

    Caching applies to fetch and to functions you explicitly cache. A plain query runs every time the component renders on the server.

Summary

  • Database code runs only on the server: Server Components, Server Actions and Route Handlers. Mark data modules with server-only.
  • Create one client per process and keep it on globalThis in development so hot reloads do not open new connections.
  • The MongoDB driver pools connections inside one MongoClient; Mongoose models need an models.X || guard.
  • Prisma generates a typed client from schema.prisma; Drizzle derives types from TypeScript table definitions.
  • Both send parameterized queries; never build SQL strings by hand.
  • On serverless platforms use a pooler or small pools, and cache queries explicitly if you want caching.

Next: Revalidation