Database With Prisma

Type-Safe SQL From Schema

Database With Prisma

Prisma is the most popular ORM in the Next ecosystem — schema-first with a fully typed generated client.

5 min read Level 2/5 #nextjs#prisma#database
What you'll learn
  • Install `prisma` and `@prisma/client`
  • Define a `schema.prisma`
  • Create a singleton `PrismaClient` and use it from server components

Prisma defines your DB schema in a single file and generates a fully typed client. The result is a database layer that feels like part of your TS code.

Install

npm i -D prisma
npm i @prisma/client
npx prisma init

Define a Schema

// prisma/schema.prisma
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id        String   @id @default(cuid())
  email     String   @unique
  name      String?
  createdAt DateTime @default(now())
}

Run npx prisma migrate dev --name init to create the migration and update the DB.

A Singleton Client

Dev mode hot-reloading can create dozens of PrismaClient instances. Cache one on globalThis:

// lib/db.ts
import 'server-only'
import { PrismaClient } from '@prisma/client'

declare global {
  // eslint-disable-next-line no-var
  var prisma: PrismaClient | undefined
}

export const db = globalThis.prisma ?? new PrismaClient()
if (process.env.NODE_ENV !== 'production') globalThis.prisma = db

Use It in a Server Component

// app/users/page.tsx
import { db } from '@/lib/db'

export default async function Page() {
  const users = await db.user.findMany()
  return (
    <ul>
      {users.map((u) => (
        <li key={u.id}>{u.email}</li>
      ))}
    </ul>
  )
}

Direct DB access from a Server Component — no API layer needed.

Database With Drizzle →