Vibe coding with Claude Code course Β· Module 14: Pinterest clone

Chests for Treasure: Boards and Saving

9 min read
In this lesson10

The Save button already shines on every pin but there is nowhere to save to. In Treasure Map pins go onto boards, which are named chests: "Islands to Visit", "Old Maps". Some chests are secret: only the owner sees them, and the people the owner invited to work together, the collaborators. Each chest also has a cover, one pin that represents it on the profile. In this lesson Claude builds the boards, the create-board window and the save-pin window. You watch the place where the agent most happily cuts corners: the lock.

What you will learn

  • order boards whose access rules live in one module and are checked on the server;
  • read the cover from coverPinId with a sensible fallback;
  • build two windows on the <dialog> from lesson 6_2 and test them with the keyboard;
  • prove with a curl command that a secret board does not leave the server for strangers.

A habit: a clean diff

This change will touch a dozen or so files, so tidy up the diff before it. If the new project does not have the PostToolUse hook from lesson 7_1 yet, ask for it in one sentence or carry over .claude/settings.json from Ship's Comms, together with Prettier in the project. The hook formats every file right after an edit, so in Source Control you see only changes in logic, not shifted indentation. Thanks to that you do not have to ask for formatting in every request.

Request for Claude Code

The step touches data, four routes, two pages and two windows, so you start with a plan:

Request for Claude Code:

/plan Add boards, that is chests for pins. lib/boards.ts: Board with ownerId,
name, description, isSecret, coverPinId, pinIds and collaboratorIds,
a demo store on globalThis. Identity only from getCurrentUserId()
in lib/session.ts (the demo-user cookie, as in lesson 11_3), never
from the body of the request. A secret board is seen by the owner and
the collaborators: the server filters it in lib/boards.ts, a stranger
gets 404. Routes: GET and POST /api/boards, POST /api/boards/[id]/pins,
DELETE /api/boards/[id] (owner only). The cover comes from coverPinId,
and when it is missing, the first pin. The create-board and save-pin
windows on <dialog> with showModal, as in lesson 6_2. Tests for the
cover and the GET route first. Finish with tests, lint,
npx tsc --noEmit and npm run build.

In the plan check one sentence: where the secret board disappears. If the plan talks about "hiding it in the component", answer that the server has to filter it out.

What Claude wrote: the rules in one place

Open lib/boards.ts in Cursor. Two small functions say who sees what and who can do what:

// lib/boards.ts
export function canView(board: Board, viewerId: string | null): boolean {
  return !board.isSecret || board.ownerId === viewerId || board.collaboratorIds.includes(viewerId ?? "");
}

export function canSavePins(board: Board, viewerId: string | null): boolean {
  return viewerId !== null && (board.ownerId === viewerId || board.collaboratorIds.includes(viewerId));
}

viewerId is the identifier of the person looking at the page, or null when nobody is logged in. A public board is seen by everyone, a secret one only by the owner and the collaborators. Only the owner and the collaborators add pins, and only the owner can delete a board. Every route and every page calls the same functions, so the rule lives in one place. When a new role arrives tomorrow, you change one file, not six.

What Claude wrote: the cover

The old code of this module checked coverPinId but showed the first pin anyway, so the field existed only for show. Claude's version:

// lib/boards.ts
export function boardCover(board: Board, pins: ReadonlyMap<string, Pin>): Pin | undefined {
  const coverId = board.coverPinId && board.pinIds.includes(board.coverPinId) ? board.coverPinId : board.pinIds[0];
  return coverId ? pins.get(coverId) : undefined;
}

coverPinId wins, but only when that pin still lies in the chest. Someone could have removed it, and a cover taken from someone else's pin would be strange. Otherwise the first pin becomes the cover, and an empty board has no cover at all, so the profile shows a grey rectangle. ReadonlyMap is a read-only map from an identifier to a pin. Four tests guard every branch. On the profile /u/captain the chest "Islands to Visit" showed for us the Lagoon from coverPinId, not the first pin of the board.

A secret board disappears on the server

Open app/api/boards/route.ts:

// app/api/boards/route.ts
export async function GET(request: Request) {
  const owner = new URL(request.url).searchParams.get("owner");
  if (!owner) return Response.json({ error: "Provide an owner." }, { status: 400 });
  const viewerId = await getCurrentUserId();
  return Response.json(listBoards(owner, viewerId).map(({ id, name, isSecret }) => ({ id, name, isSecret })));
}

listBoards filters through canView before anything leaves the server, and map sends only the fields the list needs. This is the typical agent mistake in this place: the route returns all the boards, and the component hides the secret ones with the condition !board.isSecret || isOwner. On the screen everything looks right, but the name of the secret chest flies to every browser and is visible in the Network tab. Check it with npm run dev running, as a stranger and as the owner:

curl -s -b demo-user=polly 'localhost:3000/api/boards?owner=captain'
curl -s -b demo-user=captain 'localhost:3000/api/boards?owner=captain'

-b sends a cookie, which means it pretends to be a logged-in person. For us Polly got only [{"id":"b1","name":"Islands to Visit","isSecret":false}], and the captain also got "Treasure Hideout". The board page works the same way: getBoard returns null for someone else's secret board, and the page calls notFound(). A stranger gets 404, not 403. A 403 would reveal that the board exists.

What Claude wrote: the save window

Open components/SavePinDialog.tsx. PinFeed keeps in state the pin someone wants to save, and the window opens when that pin appears:

// components/SavePinDialog.tsx
useEffect(() => {
  if (pin) dialogRef.current?.showModal();
}, [pin]);

The effect does not set state, it calls a method of the element, so the set-state-in-effect rule has nothing to hold on to. The window itself:

// components/SavePinDialog.tsx
<dialog ref={dialogRef} aria-labelledby="save-pin-title" onClose={() => { setStatus(null); onClose(); }} className="m-auto w-full max-w-sm rounded-2xl bg-white p-5 backdrop:bg-black/50">
  <h2 id="save-pin-title">Save: {pin?.title}</h2>
  <button type="button" onClick={() => dialogRef.current?.close()} aria-label="Close the save window">Γ—</button>

From lesson 6_2 you know that showModal() moves the focus into the window, Esc closes it, and m-auto puts it in the middle despite the margin reset in Tailwind 4. The onClose event arrives both after Esc and after close(), so in both cases the parent clears the selected pin. The cross has an aria-label, because the "Γ—" character alone does not tell a screen reader what the button does. Under the heading stands the list of the logged-in person's boards, with the note "(secret)" next to the secret ones. A click sends POST /api/boards/[id]/pins, and a role="status" field says whether it worked.

The create-board window, components/CreateBoardDialog.tsx, has a form with a name (required, maxLength={50}) and a "Secret board" checkbox. The POST /api/boards route checks the length of the name again, because form constraints are only hints from the browser. After success the window closes, and router.refresh() refreshes the Server Component data, so the new chest appears on the profile without a reload.

Owner actions on the server

The board page shows the Edit board and Delete buttons only when viewerId === board.ownerId. A hidden button protects nothing, though, because a request can be sent without going through the page. That is why DELETE /api/boards/[id] checks everything again, in order: identity from getCurrentUserId(), then getBoard (a missing board or someone else's secret one is 404), only then the owner (403). It deletes at the very end. For us Polly, although a collaborator, got {"error":"Only the owner can delete a board."} with a 403 when she tried to delete. The same Polly added a pin to "Islands to Visit" (201), and for the secret "Treasure Hideout" she got 404.

Under the board heading, sections are also handy: compartments in the chest, for example Caribbean and Pacific. The chosen section is a plain activeSection state of the component, and the list of visible pins is computed by the render from that state, like the columns in lesson 13_1.

Captain's review

  1. The lock on the server. Search for isSecret in components/. It may only be displayed as "(secret)", never used to filter. Then run the two curl commands from this lesson.
  2. Who is asking. Search the routes for body.ownerId and ownerId:. The owner of a new board must come from getCurrentUserId(). The agent likes to take ownerId from the form, and then anyone can create a board on someone else's account.
  3. The cover. Set coverPinId of some board to a pin from outside it and check the profile: the first pin should come back.
  4. Keyboard. Tab to the Save button, Enter, Esc. For us the focus went to the cross, and after Esc it returned to "Save pin: Bay at Dawn". The create-board window stood in the middle with the focus in the Name field. The agent often builds the window from a div and fixed inset-0. Then Esc does nothing, and Tab escapes to the page underneath.

Next step

When the review passes, ask for a commit "Boards, secret chests and saving pins". Then a small step, with a plan again: "Add board sections: sections with id, name and pinIds, switched with buttons above the grid; only the owner can add a section, which the route checks". The editor below holds a chest in miniature: a save window on <dialog>, a switch between the stranger's and the owner's view, sections and a cover from coverPinId.

Remember: a chest without a lock is just a casket, and you fit the lock in the heart of the port, on the server, not on the lid painted in the interface.

Code for this lesson: App.tsx
// A chest in miniature: a server-side lock, a cover from coverPinId, a save window on <dialog> and sections
import { useRef, useState } from 'react';

interface Pin {
  id: string;
  title: string;
  color: string;
  sectionId: string | null;
}

interface Board {
  id: string;
  ownerId: string;
  name: string;
  isSecret: boolean;
  coverPinId: string | null;
  pinIds: string[];
  collaboratorIds: string[];
}

const PINS: Pin[] = [
  { id: 'p1', title: 'Sand Under the Palm', color: '#e8c868', sectionId: 'caribbean' },
  { id: 'p2', title: 'Lagoon', color: '#a8c808', sectionId: 'caribbean' },
  { id: 'p3', title: 'Island Jungle', color: '#284858', sectionId: 'pacific' },
  { id: 'p4', title: 'Gold in the Chest', color: '#f88808', sectionId: null },
  { id: 'p5', title: 'Old Map', color: '#986848', sectionId: null },
];
const pinsById = new Map(PINS.map((pin) => [pin.id, pin]));
const SECTIONS = [
  { id: 'caribbean', name: 'Caribbean' },
  { id: 'pacific', name: 'Pacific' },
];

const BOARDS: Board[] = [
  { id: 'b1', ownerId: 'captain', name: 'Islands to Visit', isSecret: false, coverPinId: 'p2', pinIds: ['p1', 'p2', 'p3'], collaboratorIds: ['polly'] },
  { id: 'b2', ownerId: 'captain', name: 'Treasure Hideout', isSecret: true, coverPinId: null, pinIds: ['p4', 'p5'], collaboratorIds: [] },
];

// The "server": in the project these functions live in lib/boards.ts and the API routes
function canView(board: Board, viewerId: string | null) {
  return !board.isSecret || board.ownerId === viewerId || board.collaboratorIds.includes(viewerId ?? '');
}
function serverListBoards(viewerId: string | null) {
  return BOARDS.filter((board) => canView(board, viewerId));
}
function serverDeleteBoard(board: Board, viewerId: string | null) {
  return board.ownerId === viewerId ? '204: board deleted' : '403: Only the owner can delete a board.';
}
function boardCover(board: Board): Pin | undefined {
  const coverId = board.coverPinId && board.pinIds.includes(board.coverPinId) ? board.coverPinId : board.pinIds[0];
  return coverId ? pinsById.get(coverId) : undefined;
}

const VIEWERS = [
  { id: 'captain', label: 'Captain (owner)' },
  { id: 'polly', label: 'Polly (collaborator)' },
  { id: '', label: 'Stranger (not logged in)' },
];

export default function App() {
  const [viewer, setViewer] = useState('captain');
  const viewerId = viewer || null;
  const [openBoardId, setOpenBoardId] = useState('b1');
  const [activeSection, setActiveSection] = useState<string | null>(null);
  const [message, setMessage] = useState('');
  const [savedTo, setSavedTo] = useState<string | null>(null);
  const dialogRef = useRef<HTMLDialogElement>(null);

  const boards = serverListBoards(viewerId);
  const board = boards.find((b) => b.id === openBoardId) ?? boards[0];
  const visiblePins = board.pinIds
    .map((id) => pinsById.get(id))
    .filter((pin): pin is Pin => pin !== undefined && (activeSection === null || pin.sectionId === activeSection));
  const myBoards = boards.filter((b) => viewerId !== null && (b.ownerId === viewerId || b.collaboratorIds.includes(viewerId)));

  return (
    <div className="min-h-screen space-y-4 bg-amber-50 p-4 text-zinc-900">
      <label className="flex items-center gap-2 text-sm">
        Who is looking:
        <select value={viewer} onChange={(e) => { setViewer(e.target.value); setMessage(''); }} className="rounded border border-zinc-300 px-2 py-1">
          {VIEWERS.map((v) => (
            <option key={v.id} value={v.id}>{v.label}</option>
          ))}
        </select>
      </label>
      <p className="rounded bg-zinc-900 p-2 font-mono text-xs text-green-300">
        GET /api/boards?owner=captain β†’ {JSON.stringify(boards.map((b) => b.name))}
      </p>
      <ul className="grid grid-cols-2 gap-3">
        {boards.map((b) => {
          const cover = boardCover(b);
          return (
            <li key={b.id}>
              <button type="button" onClick={() => { setOpenBoardId(b.id); setActiveSection(null); }} className="w-full text-left">
                <div className="aspect-square rounded-xl" style={{ backgroundColor: cover?.color ?? '#d4d4d8' }} />
                <p className="font-semibold">{b.name}{b.isSecret ? ' (secret)' : ''}</p>
                <p className="text-xs text-zinc-500">Cover: {cover?.title ?? 'none'}</p>
              </button>
            </li>
          );
        })}
      </ul>
      <section className="rounded-xl bg-white p-3">
        <h1 className="text-lg font-bold">{board.name}</h1>
        <div className="my-2 flex flex-wrap gap-2">
          <button type="button" onClick={() => setActiveSection(null)} className={activeSection === null ? 'rounded-full bg-black px-3 py-1 text-white' : 'rounded-full bg-zinc-200 px-3 py-1'}>
            All
          </button>
          {SECTIONS.map((section) => (
            <button key={section.id} type="button" onClick={() => setActiveSection(section.id)} className={activeSection === section.id ? 'rounded-full bg-black px-3 py-1 text-white' : 'rounded-full bg-zinc-200 px-3 py-1'}>
              {section.name}
            </button>
          ))}
        </div>
        <ul className="flex flex-wrap gap-2">
          {visiblePins.map((pin) => (
            <li key={pin.id} className="rounded-lg px-3 py-6 text-sm text-white" style={{ backgroundColor: pin.color }}>
              <span className="rounded bg-black/50 px-1">{pin.title}</span>
            </li>
          ))}
        </ul>
        <div className="mt-3 flex flex-wrap gap-2">
          <button type="button" onClick={() => { setSavedTo(null); dialogRef.current?.showModal(); }} className="rounded-full bg-red-600 px-4 py-2 font-semibold text-white">
            Save pin Coral Reef
          </button>
          {viewerId === board.ownerId && (
            <button type="button" className="rounded-full bg-zinc-200 px-4 py-2">Edit board</button>
          )}
          <button type="button" onClick={() => setMessage(serverDeleteBoard(board, viewerId))} className="rounded-full bg-zinc-200 px-4 py-2">
            Send DELETE (bypassing the button)
          </button>
        </div>
        {message && <p role="status" className="mt-2 text-sm">{message}</p>}
      </section>
      <dialog ref={dialogRef} aria-labelledby="save-title" className="m-auto w-full max-w-sm rounded-2xl bg-white p-5 backdrop:bg-black/50">
        <div className="flex items-start justify-between">
          <h2 id="save-title" className="text-lg font-bold">Save: Coral Reef</h2>
          <button type="button" onClick={() => dialogRef.current?.close()} aria-label="Close the save window" className="px-2 text-xl">Γ—</button>
        </div>
        {myBoards.length === 0 ? (
          <p className="mt-3">Log in to save pins.</p>
        ) : (
          <ul className="mt-3 space-y-2">
            {myBoards.map((b) => (
              <li key={b.id}>
                <button type="button" onClick={() => setSavedTo(b.name)} className="w-full rounded-lg bg-zinc-100 px-3 py-2 text-left">
                  {b.name}{b.isSecret ? ' (secret)' : ''}
                </button>
              </li>
            ))}
          </ul>
        )}
        <p role="status" className="mt-2 text-sm">{savedTo ? 'Saved to the chest: ' + savedTo : ''}</p>
      </dialog>
      <p className="text-sm text-zinc-600">Open the save window, then press Esc: the window closes and the focus returns to the button.</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. 1. What is a board in our clone?

  2. 2. Who sees a secret board, and where is it hidden from everyone else?

These are 2 of 6 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Horizontal ordering

    Put in order the call that opens the save window as a modal:

  • Click in order

    Click the elements to build the route line that takes the identity from the cookie, not from the request body:

  • Code editor

    Create a modal for creating a board

  • Vertical ordering

    Put in order the steps of saving a pin through SavePinDialog:

  • Code editor

    Create a modal for saving a pin

  • Vertical ordering

    Put in order the steps of the route DELETE /api/boards/[id] from first to last:

  • Click in order

    Click the elements to build the click handler of a section button:

  • Horizontal ordering

    Put in order the last line of the boardCover function:

  1. QuestionQuiz: A board in Treasure Map
  2. QuestionQuiz: Who sees a secret board
  3. Put in orderSorting: Opening the dialog window
  4. Click in orderBuild: Who is asking
  5. Coding taskPractice: Create board modal
  6. QuestionQuiz: Board sections
  7. QuestionQuiz: A collaborator's rights
  8. Put in orderSorting: Saving a pin to a chest
  9. Coding taskPractice: Save pin modal
  10. QuestionQuiz: A cover from coverPinId
  11. Put in orderSorting: The checks of the DELETE route
  12. Click in orderBuild: Choosing a section
  13. QuestionQuiz: Owner actions on the server
  14. Put in orderSorting: A cover or nothing

Useful articles