LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 4318 min read

Database Integration (Prisma)

Connect a real database to a Next.js app using Prisma, and query it directly from Server Components and Server Actions.

Why Prisma

Prisma is a type-safe ORM (Object-Relational Mapper) that pairs naturally with Next.js: it generates a fully typed client from your schema, so autocomplete and type-checking cover your database queries just like any other TypeScript code.

Setting Up Prisma

npm install prisma @prisma/client
npx prisma init

This creates a prisma/schema.prisma file and a .env entry for your DATABASE_URL.

Defining a Schema

// prisma/schema.prisma
model Post {
id String @id @default(cuid())
title String
content String
createdAt DateTime @default(now())
}
npx prisma migrate dev --name init
npx prisma generate

Querying from a Server Component

A shared Prisma client instance, imported wherever needed, lets a Server Component query the database directly — as covered in the data fetching lesson, no API layer is required for internal reads.

// lib/prisma.ts
import { PrismaClient } from '@prisma/client';
export const prisma = new PrismaClient();
// app/blog/page.tsx
import { prisma } from '@/lib/prisma';
export default async function BlogPage() {
const posts = await prisma.post.findMany({ orderBy: { createdAt: 'desc' } });
return (
<ul>
{posts.map(p => <li key={p.id}>{p.title}</li>)}
</ul>
);
}

Avoiding Connection Pool Exhaustion

In development, Next.js's Fast Refresh can re-instantiate modules repeatedly, which can create a new PrismaClient — and a new database connection pool — on every reload if you're not careful.

// lib/prisma.ts
import { PrismaClient } from '@prisma/client';
const globalForPrisma = globalThis;
export const prisma = globalForPrisma.prisma ?? new PrismaClient();
if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = prisma;
}
A Very Common Gotcha

Without this pattern, a development server can silently accumulate database connections until the database itself refuses new ones — this snippet is the standard, documented fix.

FAQs

No — Drizzle ORM, Kysely, or a plain database driver all work fine. Prisma is simply one of the most popular choices in the Next.js ecosystem.

No — database clients must run on the server. Query from a Server Component, Server Action, or Route Handler, and pass the result down as data.

Summary

Prisma gives Server Components and Server Actions a type-safe, direct line to your database. Next, you'll step back and see exactly why all of this — Route Handlers, Server Actions, and direct database access — is what makes Next.js a genuinely full-stack framework.

Next Lesson →

Next.js as a Full-Stack Framework