Vibe coding with Claude Code course Β· Module 12: Medium clone

Claps and Highlights: a Server Limit and /rewind

10 min read
In this lesson10

The chronicle has its first readers. They want to show the author that they liked the text, and to highlight a sentence they will come back to after the watch. In this lesson you add both: a clap button and highlighting of passages. Both features look small and both hide a trap you cannot see at the first click.

What you will learn

  • demand a limit on the server, not only in the button, and check it with a curl command;
  • read a button that grows at once and rolls back when the server refuses;
  • count a selection from the start of the block, not from the piece of text where the mouse begins;
  • undo a failed attempt with /rewind instead of piling on another patch.

Request for Claude Code: claps

In our clone a reader can clap up to 50 times under one article. The number is arbitrary; what matters more is who guards it. The button in the browser is only a request: anyone can send a request that bypasses the page, even with a curl command. So the server checks the rule, like the lock from lesson 8_3.

Request for Claude Code:

Add claps to the article page /articles/[id]. A reader can clap
from 1 to 50 times under one article. The route
POST /api/articles/[id]/clap saves one clap and rejects the 51st
with code 409. Recognize the reader by a cookie, we have no login
yet. Keep the data in server memory. The button
components/ClapButton.tsx raises the counter at once, and when the
server refuses or the network fails, it rolls it back and shows
a message.
Done when a Vitest test shows the counter rolled back after
a 409 response, and a curl loop shows 409 at the 51st clap.

According to MDN, code 409 means that the request conflicts with the current state of the resource: the reader asks for a clap that the state of the article no longer allows.

What Claude wrote: a route with a limit

Open lib/claps.ts in Cursor. The heart of the limit is one function:

// lib/claps.ts
export function addClap(articleId: string, readerId: string): ClapResult | null {
  const { total, mine } = getClaps(articleId, readerId);
  if (mine >= MAX_CLAPS) return null;
  store.totals.set(articleId, total + 1);
  store.byReader.set(`${articleId}:${readerId}`, mine + 1);
  return { total: total + 1, mine: mine + 1 };
}

ClapResult is two numbers: the claps of all readers and the claps of this one reader. The type and the MAX_CLAPS constant live in a separate file, lib/clapRules.ts, because the button imports them too. null means "limit used up", and store is two maps in server memory. Now open the route:

// app/api/articles/[id]/clap/route.ts
export async function POST(_request: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  if (!getArticle(id)) {
    return Response.json({ error: "No such article" }, { status: 404 });
  }
  const readerId = await getOrCreateReaderId();
  const result = addClap(id, readerId);
  if (!result) {
    return Response.json({ error: `Limit is ${MAX_CLAPS} claps`, ...getClaps(id, readerId) }, { status: 409 });
  }
  return Response.json(result);
}

In Next.js 16 params is a promise, so the first line is await params, as in the Route Handlers docs. getOrCreateReaderId from lib/reader.ts reads the reader cookie through await cookies(), and when it is missing, it sets a new one with an identifier from crypto.randomUUID(). The Next.js docs allow setting cookies in Route Handlers and Server Functions. Remember that a cookie tells browsers apart, not people: whoever deletes it claps from scratch. A real reader comes only with a login, as in lesson 8_5.

What Claude wrote: a button that can roll back

Open components/ClapButton.tsx. A click raises the counter before the server answers. This is an optimistic update: you assume success so that the button reacts at once, and you clean up when there was no success:

// components/ClapButton.tsx
async function clap() {
  if (limitReached) return;
  setError("");
  setClaps((c) => ({ total: c.total + 1, mine: c.mine + 1 }));
  const ok = await fetch(`/api/articles/${articleId}/clap`, { method: "POST" })
    .then((res) => res.ok)
    .catch(() => false);
  if (!ok) {
    setClaps((c) => ({ total: c.total - 1, mine: c.mine - 1 }));
    setError("The clap did not reach the server. The counter went back.");
  }
}

limitReached is claps.mine >= MAX_CLAPS, and the same condition disables the button through disabled. The key lines are the ones with then and catch. MDN says it outright: the promise from fetch() rejects only on a network error or a bad address, and a response with an error code arrives as an ordinary success, so you have to check Response.ok. The agent's version had only .catch(...) with the rollback. In our run it passed lint and tsc, and the test with a 409 response failed with the message Unable to find role="alert": the counter stayed raised and the message did not appear at all.

The check: the 51st clap

A button disabled after 50 clicks proves nothing yet, because nobody but the button asks the server. Ask Claude for a loop that claps 51 times with one cookie, and run it while npm run dev is running:

for i in $(seq 1 51); do echo "$i $(curl -s -w ' %{http_code}' -X POST -c jar.txt -b jar.txt localhost:3000/api/articles/a3/clap)"; done | tail -3

The options -c and -b save the cookie to the file jar.txt and send it back with every request, so the server sees one reader, and tail -3 keeps the last three lines. Here is what we got:

49 {"total":94,"mine":49} 200
50 {"total":95,"mine":50} 200
51 {"error":"Limit is 50 claps","total":95,"mine":50} 409

The article started with 45 claps from the sample data, hence 95. The number at the end of a line is the response code: 50 times 200 and once 409.

Highlights: a request that drifted

A highlight is two numbers: where it starts and where it ends. A short request "Add highlighting of the selected text, render highlights as <mark>" easily ends in code that takes the numbers straight from the browser's selection: range.startOffset and range.endOffset. The first highlight comes out fine. The second, after the first in the same paragraph, lands in the wrong place.

MDN gives the reason: startOffset counts characters from the start of the text node where the selection begins, not from the start of the paragraph. After the first highlight the paragraph is already three nodes: the text before <mark>, the text inside it and the text after it. In the paragraph "Tom is fine" with "is" highlighted, the word "fine" begins in the third node at position 1, and in the text of the block at position 7. In our run the test printed expected { start: 1, end: 5 } to deeply equal { start: 7, end: 11 }.

/rewind instead of a fourth patch

It is tempting to write "fix the offsets", then "it does not work across two paragraphs", then "now the first one broke". Every patch adds an exception to a bad idea. When fixes start patching earlier fixes, undo the whole attempt. Type /rewind or press Esc twice with an empty prompt field, choose the request with the highlighting and the option "Restore code and conversation". The code and the conversation go back to the state before that request, and its text returns to the field, ready to be corrected. The limit from lesson 0_6 stays: a file changed only by a terminal command is not tracked by /rewind, and you return to the state of the last commit through Git. The new request names the trap at once:

Add highlighting in components/HighlightableArticle.tsx. A highlight
lives in one block: start and end counted from the start of the
block's text, not from the node where the selection begins. Ignore
a selection across several blocks and a highlight that overlaps
another. Functions in lib/highlights.ts with Vitest tests, also for
a selection after an existing <mark>.

What Claude wrote: numbers from the start of the block

Open lib/highlights.ts. TextRange is a pair start and end, and the function counts it from the start of the block:

// lib/highlights.ts
export function offsetsInBlock(block: HTMLElement, range: Range): TextRange | null {
  if (!block.contains(range.startContainer) || !block.contains(range.endContainer)) return null;
  const before = document.createRange();
  before.selectNodeContents(block);
  before.setEnd(range.startContainer, range.startOffset);
  const start = before.toString().length;
  const end = start + range.toString().length;
  return end > start ? { start, end } : null;
}

The first line rejects a selection that goes outside the block. Then a helper range is built from the start of the block to the start of the selection. selectNodeContents covers the whole content of the block, setEnd trims it to the place where the selection begins, and toString() returns the text of the range, according to MDN. The length of that text is start, no matter how many <mark> tags stand on the way. Rendering splits the text into pieces according to the highlights:

// lib/highlights.ts
const sorted = [...highlights].sort((a, b) => a.start - b.start);

Highlights arrive in props, and sort changes an array in place. The version highlights.sort(...) would rearrange the parent's data during rendering. In our run it passed lint and tsc, and only a test caught it (expected +0 to be 7). The pieces go into <mark> or <span> with the key seg.start, which is the position of the piece in the text.

Captain's review

  1. The limit in two places. Search the project for MAX_CLAPS: it should stand in lib/claps.ts and in the button. disabled alone is not a lock. A typical agent mistake is a limit only in the button, because the request mentioned it in one sentence.
  2. res.ok. The counter rollback must react to a refusal from the server, not only to a broken network.
  3. await params. The route and the page read params through await.
  4. Server memory. For us plain maps declared in a module did not work: after three claps through curl the article page still showed 120 and "Yours: 0/50", in next dev and in next start. The route and the page got separate copies of the module, which is why lib/claps.ts keeps the maps on globalThis.
  5. A copy before sorting. Search for .sort(: before each one stands [....

Next step

When the tests, the curl loop and the browser agree, ask for a commit "Claps and highlights". Then replies from readers under the article, with one level of nesting, like the comment tree from lesson 4_2. Add the name of the type to the request: ArticleResponse, not Response. The built-in Response type from the Fetch API already exists, and your own with the same name shadows it. In our run a route with interface Response in the same file did not pass tsc: Type 'Response' is missing the following properties from type 'Response': id, parentId. The same word twice in a message is a sign that names have collided. In the editor below waits an article with a button and highlighting: switch the agent's versions, clap at "a server that refuses" and highlight a word after an existing highlight.

Remember: the bell on deck rings as many times as the bosun allows, not as many as someone pulls the rope, and a good crew can turn the ship around before it hits the reef.

Code for this lesson: App.jsx
// Claps and highlights in miniature: a fake server with a limit and counting from the start of the block
import { useState } from 'react';

const MAX_CLAPS = 50;
const BLOCKS = [
  { id: 'b1', text: 'The storm came at night, and the crew slept after a long watch.' },
  { id: 'b2', text: 'We furled the sails before the waves grew. Everyone knew where to stand.' },
];

// A fake server: memory like the maps on globalThis in the project
const server = { total: 45, mine: 0 };

function fakeFetch(options) {
  return new Promise((resolve) => {
    setTimeout(() => {
      if (options.refuse) return resolve({ ok: false, status: 503 });
      if (!options.limitOnlyInButton && server.mine >= MAX_CLAPS) return resolve({ ok: false, status: 409 });
      server.total += 1;
      server.mine += 1;
      resolve({ ok: true, status: 200 });
    }, 300);
  });
}

// The fix: we count from the start of the block through a helper range
function offsetsInBlock(block, range, agentBug) {
  if (!block.contains(range.startContainer) || !block.contains(range.endContainer)) return null;
  if (agentBug) return { start: range.startOffset, end: range.endOffset }; // counts from the node, not from the block
  const before = document.createRange();
  before.selectNodeContents(block);
  before.setEnd(range.startContainer, range.startOffset);
  const start = before.toString().length;
  const end = start + range.toString().length;
  return end > start ? { start, end } : null;
}

function overlaps(a, b) {
  return a.start < b.end && b.start < a.end;
}

function splitText(text, highlights) {
  const sorted = [...highlights].sort((a, b) => a.start - b.start); // a copy, not the props
  const segments = [];
  let pos = 0;
  for (const h of sorted) {
    if (h.start > pos) segments.push({ start: pos, text: text.slice(pos, h.start), highlighted: false });
    segments.push({ start: h.start, text: text.slice(h.start, h.end), highlighted: true });
    pos = h.end;
  }
  if (pos < text.length) segments.push({ start: pos, text: text.slice(pos), highlighted: false });
  return segments;
}

let nextId = 1;

export default function App() {
  const [claps, setClaps] = useState({ total: server.total, mine: server.mine });
  const [error, setError] = useState('');
  const [serverView, setServerView] = useState({ ...server });
  const [refuse, setRefuse] = useState(false);
  const [onlyCatch, setOnlyCatch] = useState(false);
  const [limitOnlyInButton, setLimitOnlyInButton] = useState(false);
  const [startOffsetBug, setStartOffsetBug] = useState(false);
  const [highlights, setHighlights] = useState([]);
  const [note, setNote] = useState('');

  async function clap() {
    if (claps.mine >= MAX_CLAPS) return;
    setError('');
    setClaps((c) => ({ total: c.total + 1, mine: c.mine + 1 }));
    const res = await fakeFetch({ refuse, limitOnlyInButton });
    setServerView({ ...server });
    // The agent's version with only .catch does not roll the counter back when the server answers with an error code
    if (!res.ok && !onlyCatch) {
      setClaps((c) => ({ total: c.total - 1, mine: c.mine - 1 }));
      setError('The clap did not reach the server (' + res.status + '). The counter went back.');
    }
  }

  async function bypassButton() {
    const res = await fakeFetch({ refuse: false, limitOnlyInButton });
    setServerView({ ...server });
    setNote('Request bypassing the button: ' + res.status);
  }

  function skipTo49() {
    server.total += 49 - server.mine;
    server.mine = 49;
    setServerView({ ...server });
    setClaps({ total: server.total, mine: server.mine });
    setNote('You already have 49 claps. Clap two more times.');
  }

  function handleMouseUp() {
    const selection = window.getSelection();
    if (!selection || selection.isCollapsed) return;
    const range = selection.getRangeAt(0);
    const node = range.startContainer;
    const element = node.nodeType === 1 ? node : node.parentElement;
    const blockEl = element && element.closest('[data-block-id]');
    if (!blockEl) return;
    const offsets = offsetsInBlock(blockEl, range, startOffsetBug);
    if (!offsets) {
      setNote('The selection goes beyond one paragraph: ignoring it.');
      return;
    }
    const blockId = blockEl.dataset.blockId;
    if (highlights.some((h) => h.blockId === blockId && overlaps(h, offsets))) {
      setNote('The selection overlaps an existing highlight: ignoring it.');
    } else {
      setHighlights((prev) => [...prev, { id: 'h' + nextId++, blockId, ...offsets }]);
      setNote('Highlight: start ' + offsets.start + ', end ' + offsets.end + ' in block ' + blockId);
    }
    selection.removeAllRanges();
  }

  return (
    <div className="min-h-screen bg-gray-50 p-4 text-gray-900">
      <article onMouseUp={handleMouseUp} className="mx-auto max-w-xl space-y-3 rounded-xl bg-white p-4 shadow-sm">
        <h1 className="text-2xl font-bold">How to Survive a Storm on the Atlantic</h1>
        {BLOCKS.map((block) => (
          <p key={block.id} data-block-id={block.id} className="leading-relaxed">
            {splitText(block.text, highlights.filter((h) => h.blockId === block.id)).map((seg) =>
              seg.highlighted ? (
                <mark key={seg.start} className="bg-yellow-200">{seg.text}</mark>
              ) : (
                <span key={seg.start}>{seg.text}</span>
              ),
            )}
          </p>
        ))}
        <div className="flex flex-wrap items-center gap-3">
          <button
            type="button"
            onClick={clap}
            disabled={claps.mine >= MAX_CLAPS}
            className="rounded-full border border-gray-400 px-4 py-2 font-semibold disabled:opacity-50"
          >
            Clap
          </button>
          <span>{claps.total}</span>
          <span className="text-sm text-gray-500">Yours: {claps.mine}/{MAX_CLAPS}</span>
          {error && <span role="alert" className="text-sm text-red-700">{error}</span>}
        </div>
      </article>

      <div className="mx-auto mt-3 max-w-xl space-y-2 rounded-xl bg-gray-900 p-4 text-sm text-white">
        <p>The server remembers: total <strong>{serverView.total}</strong>, yours <strong>{serverView.mine}</strong></p>
        <div className="flex flex-wrap gap-2">
          <button type="button" onClick={skipTo49} className="rounded bg-gray-700 px-3 py-1">
            Skip to 49 claps
          </button>
          <button type="button" onClick={bypassButton} className="rounded bg-gray-700 px-3 py-1">
            Send a clap bypassing the button (like curl)
          </button>
        </div>
        {note && <p className="text-amber-300">{note}</p>}
        <label className="flex items-center gap-2">
          <input type="checkbox" checked={refuse} onChange={(e) => setRefuse(e.target.checked)} />
          The server refuses (code 503)
        </label>
        <label className="flex items-center gap-2">
          <input type="checkbox" checked={onlyCatch} onChange={(e) => setOnlyCatch(e.target.checked)} />
          Agent's bug: only .catch, no res.ok check
        </label>
        <label className="flex items-center gap-2">
          <input type="checkbox" checked={limitOnlyInButton} onChange={(e) => setLimitOnlyInButton(e.target.checked)} />
          Agent's bug: the limit only in the button
        </label>
        <label className="flex items-center gap-2">
          <input type="checkbox" checked={startOffsetBug} onChange={(e) => setStartOffsetBug(e.target.checked)} />
          Agent's bug: range.startOffset instead of counting from the start of the block
        </label>
      </div>
    </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 does it mean that ClapButton raises the clap counter optimistically?

  2. 2. Where in Captain's Chronicle must the clap limit of one reader be checked?

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, in one line, the reading of the article identifier in a Next.js 16 route:

  • Click in order

    Click the elements to build the start of a highlight from the helper range before:

  • Code editor

    Clap interaction component

  • Vertical ordering

    Put in order what happens to a highlight in the corrected version from the lesson:

  • Horizontal ordering

    Put in order, in one line, the sorting of highlights without changing the array from props:

  • Code editor

    Comments interface

  • Vertical ordering

    Put in order the undoing of the failed attempt with highlights:

  • Click in order

    Click the elements to build the route's answer to a clap over the limit:

  • Click in order

    Click the elements to build the counter rollback after the server refuses:

  1. QuestionAn optimistic counter
  2. QuestionWho guards the clap limit
  3. Put in orderReading params in a route
  4. Click in orderThe start of a highlight from the start of the block
  5. Coding taskPractice: Clap button
  6. QuestionA 409 response and only .catch
  7. Put in orderA highlight step by step
  8. QuestionAn offset counted from the node
  9. Put in orderSorting a copy of the highlights
  10. Coding taskPractice: Response section
  11. QuestionThe third highlight patch
  12. QuestionThe name of the reply type
  13. Put in orderUndoing with /rewind
  14. Click in orderThe 409 answer from the route
  15. Click in orderRolling the counter back

Useful articles