So far our To-Do API forgets everything when it restarts, because tasks live in memory. Now we give it a real memory: a PostgreSQL database. By the end of this lesson, tasks survive restarts, crashes and deploys.
How the pieces fit
- 1
βοΈ
You write schema.prisma
Describe the User and Task tables in a simple language.
- 2
π§Ύ
prisma migrate dev
Prisma writes the SQL (a migration file) and runs it: the tables now exist.
- 3
βοΈ
prisma generate
Prisma creates a typed client that knows your tables.
- 4
π»
Your service uses it
prisma.task.create({ data: { title } }) inserts a row.
Step 1: Get a PostgreSQL database
Pick whichever is easiest for you. You only need a connection string at the end.
| Option | How | Best for |
|---|---|---|
| Docker | One command (below) | If you already have Docker |
| Install locally | Postgres.app (Mac), the official installer (Windows), or your package manager (Linux) | Working offline |
| Free cloud | Create a free project on Neon or Supabase and copy the connection string | Zero installation |
# Option A: run PostgreSQL in Docker (user postgres, password postgres, database tasks_app)$docker run --name tasks-db -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=tasks_app -p 5432:5432 -d postgres
A connection string looks like this. Each part is a piece of the address:
postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=public
# With the Docker command above:
postgresql://postgres:postgres@localhost:5432/tasks_app?schema=publicStep 2: Install Prisma
$bun add @prisma/client@7 @prisma/adapter-pg@7 pg$bun add -d prisma@7 @types/pg
Step 3: Set up Prisma in the project
$bunx --bun prisma init --datasource-provider postgresql
This creates three things:
prisma/schema.prisma: where you describe your tables.prisma7.config.ts: tells Prisma where the schema and migrations are and which database to use.- A
DATABASE_URLline in.env. Replace it with your connection string.
It may also add a few small folders with tips for AI coding assistants; you can delete them. Here's the config file it made:
// This file was generated by Prisma, and assumes you run Prisma commands using `bun --bun run prisma [command]`.
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations",
},
datasource: {
url: env("DATABASE_URL"),
},
});Step 4: Describe your tables
Open prisma/schema.prisma and describe our two tables, User and Task:
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
datasource db {
provider = "postgresql"
}
model User {
id Int @id @default(autoincrement())
email String @unique
password String
name String
tasks Task[]
createdAt DateTime @default(now())
}
model Task {
id Int @id @default(autoincrement())
title String
done Boolean @default(false)
userId Int
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}Each line is fieldName Type @extras. The extras you'll use most:
| Write this | It means |
|---|---|
| @id @default(autoincrement()) | The id: 1, 2, 3β¦ filled in automatically |
| @unique | No two rows can have the same value (one account per email) |
| @default(false) / @default(now()) | The value if you don't give one |
| @updatedAt | Automatically set to the time of the last change |
| String? (with a ?) | Optional: this field can be empty (null) |
| tasks Task[] | A user has many tasks (not a real column, a link) |
| @relation(fields: [userId], references: [id], onDelete: Cascade) | Each task belongs to a user; delete the user and their tasks go too |
Step 5: Add database scripts
Add these to the scripts in package.json. --env-file=.env makes sure Prisma can read your DATABASE_URL:
{
"scripts": {
"dev": "bun --watch src/server.ts",
"db:migrate": "bun --bun --env-file=.env run prisma migrate dev",
"db:generate": "bun --bun --env-file=.env run prisma generate",
"db:studio": "bun --bun --env-file=.env run prisma studio"
}
}Step 6: Run your first migration
This is the magic moment. One command turns your schema into real tables:
$bun run db:migrate --name init$bun run db:generate
When we ran it, Prisma replied:
Applying migration `20261119133917_init`
The following migration(s) have been created and applied from new schema changes:
prisma/migrations/
ββ 20261119133917_init/
ββ migration.sql
Your database is now in sync with your schema.
β Generated Prisma Client (7.10.1) to ./generated/prismaPrisma wrote the SQL for you and saved it. You never have to write this yourself, but it's good to see what it did:
-- CreateTable
CREATE TABLE "User" (
"id" SERIAL NOT NULL,
"email" TEXT NOT NULL,
"password" TEXT NOT NULL,
"name" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Task" (
"id" SERIAL NOT NULL,
"title" TEXT NOT NULL,
"done" BOOLEAN NOT NULL DEFAULT false,
"userId" INTEGER NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Task_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
-- AddForeignKey
ALTER TABLE "Task" ADD CONSTRAINT "Task_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;Step 7: Create the database client
Make one shared client for the whole app. Every service imports it from here:
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "../../generated/prisma/client";
import { env } from "../config/env";
// One shared database client for the whole app.
const adapter = new PrismaPg({ connectionString: env.DATABASE_URL });
export const prisma = new PrismaClient({ adapter });π‘Import PrismaClient from the generated folder, not from @prisma/client. That's the Prisma 7 way.
Step 8: Read and write data
Now any service can use the database with simple, typed functions. These are the ones you'll use 90% of the time:
// CREATE a row
await prisma.task.create({ data: { title: "Buy milk", userId: 1 } });
// READ many rows (with a filter, order and limit)
await prisma.task.findMany({ where: { userId: 1, done: false }, orderBy: { createdAt: "desc" }, take: 10 });
// READ one row by a unique field
await prisma.user.findUnique({ where: { email: "[email protected]" } });
// READ the first row that matches any filter
await prisma.task.findFirst({ where: { id: 5, userId: 1 } });
// UPDATE a row
await prisma.task.update({ where: { id: 5 }, data: { done: true } });
// DELETE a row
await prisma.task.delete({ where: { id: 5 } });
// COUNT rows
await prisma.task.count({ where: { userId: 1 } });Changing tables later: a new migration
Your app grows. Say tasks need an optional due date. You never edit the database by hand. You change the schema and make a new migration:
done Boolean @default(false)
dueDate DateTime? // new, optional$bun run db:migrate --name add_due_date$bun run db:generate
Prisma compares your schema with the database and writes only the difference. This is the file it made for us:
-- AlterTable
ALTER TABLE "Task" ADD COLUMN "dueDate" TIMESTAMP(3);Commit the prisma/migrations folder to Git. It's the history of your database: anyone can rebuild the same tables from it.
See your data: Prisma Studio
$bun run db:studio
This opens a simple web page where you can see and edit the rows in your tables. Great for checking that your API really saved something.
On the real server: migrate deploy
| Command | Where | What it does |
|---|---|---|
| prisma migrate dev | Your laptop only | Creates new migration files from schema changes and applies them |
| prisma migrate deploy | Production server | Applies existing migration files only. Never creates new ones, never asks questions |
| prisma generate | Everywhere, after install | Builds the typed client from the schema |
Key takeaways
- βPostgreSQL keeps the data; Prisma lets you use it from TypeScript with full autocomplete.
- βInstall Prisma 7 explicitly (@7) with the pg driver and @prisma/adapter-pg.
- βDescribe tables in schema.prisma; migrations turn those descriptions into real tables.
- βEvery schema change becomes a new, numbered migration file you commit to Git.
- βUse one shared PrismaClient from src/lib/prisma.ts across the whole app.
Frequently asked questions
What is Prisma?
Prisma is an ORM: a tool that lets you work with the database using TypeScript instead of writing SQL by hand. You describe your tables in schema.prisma, Prisma creates them with migrations, and gives you a typed client like prisma.task.create().
What is a database migration?
A migration is a saved, numbered SQL file that changes your database structure, like 'create the Task table' or 'add a dueDate column'. Running migrations in order rebuilds the exact same tables on any computer or server.
Why PostgreSQL?
It's free, open source, very reliable and used everywhere from small startups to huge companies. Every cloud offers it, and it handles both simple apps and very large ones.
migrate dev or migrate deploy?
Use `prisma migrate dev` on your laptop: it creates new migration files from your schema changes and applies them. Use `prisma migrate deploy` on the real server: it only applies migration files that already exist, and never creates new ones.
Should I use Prisma 7 or Prisma 8?
This course uses Prisma 7, the current stable version. Prisma 8 is in release candidate and changes the query style. Because npm's 'latest' tag may point to Prisma 8, always install with @7, as shown here.
Do I need to install PostgreSQL on my computer?
No. You can run it with one Docker command, or use a free cloud database like Neon or Supabase and just paste its connection string into .env.
π§ Quick check: database and Prisma
1. Where do you describe your tables with Prisma?
2. You added a dueDate field to the Task model. What do you run on your laptop?
3. What does @unique on email do?
4. Should you edit a migration file that's already been applied?
Checking your accessβ¦