→ cards/11-prisma7

Chapter

11 · Prisma 7 (SQLite-first, App Router)

Prisma 7 setup for Next 14–16: env, schema, client, upgrade path, and rules of use.

Scope

  • ORM: Prisma 7 (engineType: binary, Node runtime).
  • Runtime: Next.js App Router (14–16), Turbopack-friendly.
  • Default DB: SQLite; portable to Postgres/MySQL.
  • Goal: safe dev HMR, explicit env, clean upgrade from Prisma 5.

Install + Init

npm install prisma@latest @prisma/client@latest
npx prisma init

.env (root, required)

DATABASE_URL="file:./dev.db"

schema.prisma (SQLite)

generator client {
  provider = "prisma-client-js"
}

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

model User {
  id        Int      @id @default(autoincrement())
  email     String   @unique
  name      String?
  posts     Post[]
  createdAt DateTime @default(now())
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  authorId  Int
  author    User     @relation(fields: [authorId], references: [id])
  createdAt DateTime @default(now())
}

lib/prisma.ts (client)

import { PrismaClient } from "@prisma/client";

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

const prisma =
  globalForPrisma.prisma ??
  new PrismaClient({
    engineType: "binary",
    log: process.env.NODE_ENV === "development" ? ["query", "error", "warn"] : ["error"],
  });

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

export default prisma;

Commands

npx prisma generate
npx prisma db push
npx prisma validate
npx prisma env

Usage Rule

  • Use prisma only in server components/actions/route handlers.
  • Never in client components.

Prisma 5 → 7 Upgrade

  • Remove prisma.config.ts and defineConfig imports.
  • Add engineType: "binary"; rerun generate.

SQLite → Postgres

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

DATABASE_URL="postgresql://user:pass@localhost:5432/db"

npx prisma migrate dev