Vibe coding with Claude Code course Β· Module 14: Pinterest clone
The Treasure Register: A Database for Pins and Boards
In this lesson13
Create a board called "Market Maps" then stop the server and start it again. The board is gone. The chests from lesson 13_2 sit in a store on globalThis, which is the memory of a single Node process, and the pins sit in a list in lib/pins.ts. Every restart begins from zero, and what you need is a harbour ledger that survives a storm: a database. To talk to it Claude will use Prisma ORM. An ORM is a library that turns table rows into TypeScript objects, so instead of writing SQL by hand you call prisma.board.findMany() and get types.
What you will learn
- tell Claude to read the documentation of the right version before it installs anything, and spot the version trap;
- run a local database with no account and no Docker, and enter its address so that the agent never sees it;
- read the SQL migration before it touches the database;
- move boards into the database while the access rules from lesson 13_2 stay unchanged.
Four words before the voyage
The schema (prisma/schema.prisma) describes the tables in the Prisma language. A migration is an SQL file that turns yesterday's database into today's, and it goes into the repository. The client is TypeScript code generated from the schema, with a method for every table. The adapter is the driver through which the client connects to PostgreSQL.
A catch from the calendar, as of November 2026: under the latest tag npm gives Prisma ORM 8, still a release candidate. Prisma 7 is fully supported and the course stays with it, so the first order is: read the documentation of version 7.
Request for Claude Code
The database address is a secret, so the project needs the deny rules for .env from lesson 8_4. If treasure-map does not have them yet, move them into .claude/settings.json with one sentence. The change touches dependencies, the schema, data and several routes, so you start with a plan:
Request for Claude Code:
/plan Move the boards from the globalThis store to a PostgreSQL
database through Prisma ORM version 7, not 8. Before you install
anything, read the Prisma 7 documentation: the Next.js guide and the
page about the local prisma dev database. Always install with a version
number. Models Pin, Board and PinOnBoard (a pin on a board, the pair is
unique). The seed moves the pins from lib/pins.ts and both boards from
lesson 13_2. lib/boards.ts reads the database, while canView and
canSavePins stay unchanged. The database address comes only from an
environment variable; you do not read .env, I will paste addresses
myself. Create the migration with --create-only and wait until I have
read the SQL. Done when tests, lint, npx tsc --noEmit and npm run build
pass.In the plan check two things: whether every install command has a version number, and whether the plan stops before applying the migration.
What Claude wrote: installing with a number
The first commands come from the Prisma 7 guide for Next.js. The documentation writes prisma@prev there, which today means the same version as prisma@7:
npm install prisma@7 tsx @types/pg --save-dev
npm install @prisma/client@7 @prisma/adapter-pg dotenv pg
npx prisma --versionThe first line installs the command-line tool (CLI), the second the application library with the adapter and the pg driver. In our run --version showed version 7 for both packages. A typical agent mistake is npm install prisma without a number. That brings the CLI in version 8 RC, which according to the documentation does not read schema.prisma and knows neither generate nor migrate dev. You will recognise it by npx prisma --version or by "prisma": "^8.0.0-rc..." in package.json. A second trap waits further on: the version 7 CLI shows an "Update available" box with the advice npm i --save-dev prisma@latest. Neither you nor Claude follows that advice.
What Claude wrote: configuration
Claude ran npx prisma init --output ../app/generated/prisma --no-skills. --output is the path from the Next.js guide, and --no-skills skips installing the Prisma skills for agents, which init would otherwise download from the network into .claude/skills. It created prisma/schema.prisma, .env and a configuration file:
// prisma7.config.ts
import "dotenv/config";
import { defineConfig } from "prisma/config";
export default defineConfig({
schema: "prisma/schema.prisma",
migrations: { path: "prisma/migrations", seed: "tsx prisma/seed.ts" },
datasource: {
url: process.env["DATABASE_URL"],
shadowDatabaseUrl: process.env["SHADOW_DATABASE_URL"],
},
});The file is called prisma7.config.ts: that is what Prisma has called it since version 7.10, although many documentation pages still write prisma.config.ts. Prisma 7 does not load .env by itself, hence import "dotenv/config" in the first line. Addresses come only from variables. The shadow database is a second, scratch database in which migrate dev replays the migrations to check that they match the schema. It does not touch your data.
A database on board: prisma dev
Prisma itself provides the local database: prisma dev starts PostgreSQL on your computer, with no account and no Docker. In a second terminal tab in Cursor type:
npx prisma dev --name treasure-mapThe name keeps this project's database apart from others. The documentation tells you to press h and copy two postgres:// addresses into .env. You paste them yourself, because the deny rule blocks Claude from reading that file, and from writing it too:
# .env (copy the ports from the screen, yours will differ)
DATABASE_URL="postgres://postgres:postgres@localhost:<database port>/template1?sslmode=disable"
SHADOW_DATABASE_URL="postgres://postgres:postgres@localhost:<shadow port>/template1?sslmode=disable"The prisma+postgres:// address that init wrote does not work with the adapter: in our run it ended with Connection terminated unexpectedly. Without the second address the first migration passes and the next ones fail with relation "..." already exists, which the documentation describes and which we saw on "Pin".
What Claude wrote: the schema
Open prisma/schema.prisma. The pin got the same fields as the type from lesson 13_1, plus an owner:
model Pin {
id String @id @default(cuid())
ownerId String
author String
title String
src String
width Int
height Int
dominantColor String
tags String[]
createdAt DateTime @default(now())
boards PinOnBoard[]
}@id @default(cuid()) means a primary key that the database fills with a random string when you do not give one. String[] is a list of strings that PostgreSQL keeps in a single column. Board has the fields from lesson 13_2 except pinIds. In their place it gets the field pins PinOnBoard[], that is, its own entries from the join table described below, and also @@index([ownerId]), because the profile looks boards up by owner. The pins on boards are described by a separate model:
model PinOnBoard {
pinId String
boardId String
savedAt DateTime @default(now())
pin Pin @relation(fields: [pinId], references: [id], onDelete: Cascade)
board Board @relation(fields: [boardId], references: [id], onDelete: Cascade)
@@id([pinId, boardId])
}This is a join table: one row is one pin on one board. @@id([pinId, boardId]) makes the pair a key, so the same pin cannot land twice in the same chest. onDelete: Cascade removes the entries together with the board, but the pins themselves stay.
The migration: you read first
Claude ran npx prisma migrate dev --name init --create-only. That flag creates the migration file but does not apply it. Open prisma/migrations/<date>_init/migration.sql in Cursor. The most important fragment:
CREATE TABLE "PinOnBoard" (
"pinId" TEXT NOT NULL,
"boardId" TEXT NOT NULL,
"savedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "PinOnBoard_pkey" PRIMARY KEY ("pinId","boardId")
);You look for three things: the tables you expect, the key made of a pair, and no DROP, because in later migrations DROP COLUMN deletes data. You do the reading, because /rewind undoes files changed by Claude's tools, not the contents of a database. The official Prisma prompt for agents also says to stop and ask when migrate dev wants to wipe the database. When the SQL matches, you answer "apply" and Claude runs npx prisma migrate dev. In our run: Your database is now in sync with your schema.
generate and seed separately
In Prisma 7 migrate dev no longer generates the client or runs the seed, even though its CLI help still mentions it. In our run the app/generated folder did not exist after the migration. That is why the next two commands:
npx prisma generate
npx prisma db seedThe first reported the client in ./app/generated/prisma, and the seed printed Pins: 36, boards: 2. The seed clears the tables and copies in the pins from lib/pins.ts and both boards with the ids b1 and b2, so the curl commands from lesson 13_2 work unchanged.
What Claude wrote: one client
Open lib/prisma.ts:
// lib/prisma.ts
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "@/app/generated/prisma/client";
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter });
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;In development mode Next.js reloads modules from scratch, and a client remembered on globalThis survives the reload without opening new connections. The import comes from the folder produced by generate, not from @prisma/client. Without the adapter Prisma 7 refuses: A driver adapter is required to connect to your database. dotenv is not needed here, because Next.js loads .env itself.
What Claude wrote: boards from the database
In lib/boards.ts the Board type and the functions canView, canSavePins and boardCover stayed word for word. Only the functions that reach for data changed:
// lib/boards.ts
export async function listBoards(ownerId: string, viewerId: string | null): Promise<Board[]> {
const rows = await prisma.board.findMany({ where: { ownerId }, include: withPins, orderBy: { createdAt: "asc" } });
return rows.map(toBoard).filter((board) => canView(board, viewerId));
}include tells Prisma to fetch the related rows in the same query. The constant withPins says which: only the pinId values from PinOnBoard, in the order they were saved. toBoard turns a row into the familiar shape with pinIds, so the cover tests from lesson 13_2 passed unchanged. The canView filter still stands in the application code: Prisma connects as the owner of the tables and will not put any lock in place for you. The functions are asynchronous now, so pages and routes got an await. Saving a pin on a board is an upsert on the pair pinId_boardId, that is, "add it or leave it".
Captain's review
- Versions and adapter. In the diff of
package.jsonyou look for"prisma": "^7and"@prisma/client": "^7, and inlib/prisma.tsfor the client with{ adapter }and the address fromprocess.env. - A secret outside Git. There is no
.envin Source Control: the.env*line from the.gitignoreofcreate-next-apphides it, whichgit check-ignore -v .envwill show. - A unique pair.
@@id([pinId, boardId])in the schema andPRIMARY KEY ("pinId","boardId")in the SQL. In our run two identicalPOST /api/boards/b1/pinsgave 201 twice and one row, and a manual secondcreateended with the errorP2002. - The migration was read. You opened every file in
prisma/migrationsin Cursor before Claude applied it. Neither/rewindnorgit restorewill undo a change in the database.
Finally, the proof: create a board with the curl from lesson 13_2, stop the server and start it again. In our run "Market Maps" came back on the list. The test from lesson 13_2 failed twice along the way: first because Vitest does not read .env by itself (Claude added loadEnv to vitest.config.mts), then because of the new board. Tests on a shared database depend on its state, so before them you run npx prisma db seed.
Next step
When the review passes, ask for a commit "Boards and pins in a Prisma 7 database" and check that .env did not slip into the changes. The home page and GET /api/pins still read the list from lib/pins.ts, and there is no way to add a pin: that is the job of the next lesson. After work, stop the database: npx prisma dev stop treasure-map. In the editor below waits the register in miniature: untick steps, change the version and the address, and watch which message appears first.
Remember: treasure buried in the sand disappears with the tide, so you write it in the ledger, and you read every page of that ledger before you press the seal.
Code for this lesson: App.tsx
// The treasure register in miniature: the Prisma 7 steps and what breaks when one is missing
import { useState } from 'react';
type StepId = 'migrate' | 'generate' | 'seed' | 'adapter';
interface Step {
id: StepId;
command: string;
what: string;
}
const STEPS: Step[] = [
{ id: 'migrate', command: 'npx prisma migrate dev', what: 'tables in the database (SQL read before it is applied)' },
{ id: 'generate', command: 'npx prisma generate', what: 'the client in app/generated/prisma' },
{ id: 'seed', command: 'npx prisma db seed', what: 'the starting pins and boards' },
{ id: 'adapter', command: 'new PrismaClient({ adapter })', what: 'the client with the PrismaPg adapter in lib/prisma.ts' },
];
type Install = 'pinned' | 'unpinned';
type Address = 'postgres' | 'ppg';
interface RunResult {
ok: boolean;
lines: string[];
}
// The first error you see after opening /u/captain. The messages come from real runs.
function openProfile(done: Record<StepId, boolean>, install: Install, address: Address): RunResult {
if (install === 'unpinned') {
return { ok: false, lines: ['npm install prisma (no version number) brought the CLI in version 8 RC.', 'npx prisma generate: No command registered for generate', 'Check npx prisma --version and install prisma@7.'] };
}
if (!done.generate) {
return { ok: false, lines: ['migrate dev in Prisma 7 no longer generates the client.', "Cannot find module '@/app/generated/prisma/client'", 'Run npx prisma generate.'] };
}
if (!done.adapter) {
return { ok: false, lines: ['PrismaClient was instantiated without any options.', 'A driver adapter is required to connect to your database.'] };
}
if (address === 'ppg') {
return { ok: false, lines: ['The prisma+postgres:// address from prisma init does not work with PrismaPg.', 'Error: Connection terminated unexpectedly', 'Paste the postgres:// address from npx prisma dev into .env.'] };
}
if (!done.migrate) {
return { ok: false, lines: ['P2021 The table public.Board does not exist in the current database.', 'Migration first: --create-only, read the SQL, then migrate dev.'] };
}
if (!done.seed) {
return { ok: true, lines: ['The page works, but the captain profile is empty: 0 boards.', 'migrate dev in Prisma 7 does not run the seed. Run npx prisma db seed.'] };
}
return { ok: true, lines: ['Boards: Islands to Visit (3 pins), Treasure Hideout (2 pins, secret).', 'Restart the server: the boards stay, because they live in the database, not on globalThis.'] };
}
function secondMigration(shadow: boolean): RunResult {
return shadow
? { ok: true, lines: ['Applying migration ..._add_index', 'Your database is now in sync with your schema.'] }
: { ok: false, lines: ['Without SHADOW_DATABASE_URL the first migration passes, the next ones do not:', 'ERROR: relation "Pin" already exists'] };
}
export default function App() {
const [done, setDone] = useState<Record<StepId, boolean>>({ migrate: true, generate: false, seed: false, adapter: true });
const [install, setInstall] = useState<Install>('pinned');
const [address, setAddress] = useState<Address>('postgres');
const [shadow, setShadow] = useState(true);
const [result, setResult] = useState<RunResult | null>(null);
return (
<div className="min-h-screen space-y-4 bg-amber-50 p-4 text-zinc-900">
<h1 className="text-xl font-bold">Treasure register: the Prisma 7 order</h1>
<div className="flex flex-wrap gap-3 text-sm">
<label className="flex items-center gap-2">
Install:
<select value={install} onChange={(e) => setInstall(e.target.value as Install)} className="rounded border border-zinc-300 px-2 py-1">
<option value="pinned">prisma@7 and @prisma/client@7</option>
<option value="unpinned">prisma without a version number</option>
</select>
</label>
<label className="flex items-center gap-2">
Address in .env:
<select value={address} onChange={(e) => setAddress(e.target.value as Address)} className="rounded border border-zinc-300 px-2 py-1">
<option value="postgres">postgres:// from prisma dev</option>
<option value="ppg">prisma+postgres:// from prisma init</option>
</select>
</label>
</div>
<ol className="space-y-2">
{STEPS.map((step) => (
<li key={step.id} className="rounded-xl bg-white p-2">
<label className="flex items-center gap-2">
<input type="checkbox" checked={done[step.id]} onChange={(e) => setDone({ ...done, [step.id]: e.target.checked })} />
<code className="font-semibold">{step.command}</code>
</label>
<p className="ml-6 text-sm text-zinc-600">{step.what}</p>
</li>
))}
</ol>
<div className="flex flex-wrap items-center gap-2">
<button type="button" onClick={() => setResult(openProfile(done, install, address))} className="rounded-full bg-red-600 px-4 py-2 font-semibold text-white">
Open /u/captain
</button>
<button type="button" onClick={() => setResult(secondMigration(shadow))} className="rounded-full bg-zinc-200 px-4 py-2">
Second migration
</button>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={shadow} onChange={(e) => setShadow(e.target.checked)} />
SHADOW_DATABASE_URL in .env
</label>
</div>
{result && (
<ul role="status" className={result.ok ? 'space-y-1 rounded-xl bg-emerald-100 p-3 font-mono text-sm' : 'space-y-1 rounded-xl bg-red-100 p-3 font-mono text-sm'}>
{result.lines.map((line) => (
<li key={line}>{line}</li>
))}
</ul>
)}
<p className="text-sm text-zinc-600">Untick one step at a time and see which message appears first.</p>
</div>
);
}Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is Prisma ORM in Treasure Map?
2. How do you fetch boards together with their entries from the PinOnBoard join table with one findMany call?
Hands-on tasks in the game
- Click in order
Click the elements to build the expression from lib/prisma.ts that creates the Prisma 7 client (one element is redundant):
- Code editor
Create a Prisma model and queries
- Vertical ordering
Put in order the steps by which the Treasure Map boards got into the database in Prisma 7: