Back to results for “Environment Variables & Configuration”
Next.js › Database Integration with Next.js

How do you connect a database to a Next.js application?

Beginner

Answer

You typically install a database client or an ORM library like Prisma, set up a connection string in your environment variables, and then call database queries directly inside server components, route handlers, or server actions, since these all run on the server where database credentials are safe.
// lib/db.js
import { PrismaClient } from '@prisma/client';

export const db = new PrismaClient();

// app/page.js
import { db } from '@/lib/db';

export default async function Page() {
  const posts = await db.post.findMany();
  return <div>{posts.length} posts found</div>;
}
Real-world example A recipe sharing app connects to a PostgreSQL database using Prisma, letting server components query recipes directly without needing a separate API layer in between.

Common follow-ups: Why is it unsafe to connect directly to a database from a client component?;What is an ORM and why do many teams prefer using one?