Vibe coding with Claude Code course ยท Module 12: Medium clone
A Newsroom Under One Flag: Publications, Permissions and Recommendations
In this lesson9
One author is one boat but the chronicle grows into a fleet. The captain wants publications, that is a shared page of several authors with their own crew: the owner manages it, the editor publishes texts, and the writer submits them. A question appears that is easy to miss in code: who can really press "Publish"? In this lesson you build a publication page from a sketch, guard permissions on the server and add recommendations that you can explain to someone.
What you will learn
- give Claude your own sketch as part of the request;
- read tabs described by a type instead of
as any, and a list with stable keys; - check a permission on the server and prove it with a
curlcommand; - order a recommendation score that can be described in one sentence.
A sketch as a request
The layout of a page is hard to describe in words, so you show it with a drawing, as in lesson 3_2. Draw your own sketch on a piece of paper: the name of the publication and the number of followers at the top, three tabs below them, a list of titles under that. Draw your own idea; do not redraw or paste a screenshot of someone else's platform. Save a photo of the paper in the project as sketches/publication.jpg. The sketch says how the page looks, and the text of the request says how it works and who can do what.
Request for Claude Code:
/plan First describe the sketch sketches/publication.jpg in a few
sentences. Then plan the page /publications/[slug] laid out as in
the sketch: the name and the number of followers, tabs Latest, Top
and About us, a list of articles. Types in types/publication.ts,
sample data in lib/publications.ts. Roles: owner, editor, writer.
Only owner and editor publish: the route
POST /api/articles/[id]/publish checks the role on the server and
returns 403 to the others. There is no login: who you are is told
by the demo-user cookie in lib/session.ts. No as any.
Done when curl as writer gets 403 and as editor 200, and
npm run lint, npx tsc --noEmit and npm run build pass.Read the description of the sketch at the start of the plan. If Claude got wrong where the tabs stand, correct the plan before any code exists.
What Claude wrote: roles and one permission
Open types/publication.ts in Cursor. A role is one of three names, and a publication member connects a person with a role:
// types/publication.ts
export type Role = "owner" | "editor" | "writer";
export interface PublicationMember {
userId: string;
name: string;
role: Role;
}Publication in the same file also has a slug, a name, a description, the number of followers and a list of members. A permission follows from the role, so in lib/publications.ts stands one function instead of several true-false fields scattered across the data:
// lib/publications.ts
// The owner and the editor publish. The writer only submits a text.
export function canPublish(role: Role | undefined): boolean {
return role === "owner" || role === "editor";
}undefined is someone from outside the publication's crew: for them the function returns false. One function is one place to change when the captain decides that writers may publish too.
What Claude wrote: tabs with a type
Open components/PublicationTabs.tsx. The list of tabs has as const at the end:
// components/PublicationTabs.tsx
const TABS = [
{ key: "latest", label: "Latest" },
{ key: "top", label: "Top" },
{ key: "about", label: "About us" },
] as const;
type TabKey = (typeof TABS)[number]["key"];as const tells TypeScript that key is exactly "latest", "top" or "about", not any string. TabKey pulls these three names out of the array, so a new tab added to TABS lands in the type at once. A click is a plain onClick={() => setTab(t.key)}, with no casting.
A typical agent path looks different. A tab type written separately and an array without as const gave us a tsc error: Argument of type 'string' is not assignable to parameter of type 'SetStateAction<TabKey>'. The quickest "fix" is setTab(t.key as any), which silences the compiler. npm run lint did not let it through: Unexpected any. Specify a different type. When Claude proposes as any, ask for a type that fits, as in lesson 1_4.
What Claude wrote: a key from the data
The list of articles sorts a copy of the data according to the tab, and every element gets a key from the article's identifier:
// components/PublicationTabs.tsx
{sorted.map((article) => (
<li key={article.id}>sorted is [...articles].sort(...): by date for Latest, by claps for Top. The React docs warn against an index as a key exactly when the order changes: with key={i} React will, after a tab switch, match state and elements by position, not by article. They also warn against key={Math.random()}, which recreates the whole list on every render.
A lock on the server
The "Publish" button shows only for members with canPublish. That is a convenience, not a safeguard: a request can be sent without the page. A typical agent mistake is checking the role only in the component and calling the matter closed. So the route decides:
// app/api/articles/[id]/publish/route.ts
export async function POST(_request: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const article = getArticle(id);
if (!article) {
return Response.json({ error: "No such article" }, { status: 404 });
}
const role = roleIn(article.publication, await getCurrentUserId());
if (!canPublish(role)) {
return Response.json({ error: "Only the owner and editors publish" }, { status: 403 });
}
publishArticle(id);
return Response.json({ id, status: "published" });
}roleIn looks up the role of a person in the article's publication, and getCurrentUserId from lib/session.ts reads the demo-user cookie. This is a pretend login, needed only for learning: in a real app the identifier comes from the session from lesson 8_5. Check the lock from the terminal, as a writer and as an editor:
curl -s -X POST -b "demo-user=u-jack" localhost:3000/api/articles/a4/publish -w ' %{http_code}\n'
curl -s -X POST -b "demo-user=u-bill" localhost:3000/api/articles/a4/publish -w ' %{http_code}\n'For us the writer Calico Jack got {"error":"Only the owner and editors publish"} 403, and the editor Billy Bones got {"id":"a4","status":"published"} 200. In the browser, after setting the editor's cookie in the developer tools console, a click on "Publish" moved the text to the Latest list.
Recommendations you can explain
The home page should show the reader texts meant for them. A request "add a recommendation algorithm" can end in an empty comment like "algorithm here" or in a formula with weights nobody can justify. It is better to order a rule you can check on your fingers: "In lib/recommend.ts add a score: 3 for every followed topic, 2 for a followed author, 1 for every full 100 claps, but at most 3 for claps. Write the rule in a comment above the function and add a test with the scores of sample articles."
// lib/recommend.ts
export function score(article: Article, reader: Reader): number {
const topics = article.topics.filter((t) => reader.followedTopics.includes(t)).length;
const author = reader.followedAuthors.includes(article.authorId) ? 1 : 0;
const claps = Math.min(3, Math.floor(article.claps / 100));
return 3 * topics + 2 * author + claps;
}Reader is the lists of topics and authors that the reader follows. recommend sorts a copy of the articles by score, and on a tie the newer one wins. The limit for claps has a reason: with a point for every 10 claps and no upper bound, "The Treasure Map" with 340 claps would get 34 points and cover every followed topic. For us the test counted, for a reader who follows sailing and the cook Mary, the scores { a1: 4, a2: 3, a3: 5, a4: 3 }.
Captain's review
- The lock. The permission is checked by the route, not only by a hidden button. The
curlcommands as writer and editor are your proof. - Types instead of casting. Search the project (Cmd+Shift+F) for
as any: zero hits, andnpm run lintends without errors. - Keys. Every
key=in the lists is an identifier from the data, not an index and notMath.random(). - The score. The comment above
scoredescribes the rule in one sentence, and the test checks concrete numbers. - Server memory.
publishArticleadds the identifier to a set onglobalThis, like the claps in lesson 11_2. The first version changed thestatusfield in the module's data: for us the route answered 200, and after a refresh the page still showed the text as submitted, because the route changed its own copy of the data.
Next step
Ask for a commit "Publications, permissions and recommendations". Then the home page. The change touches at least three files, so start with a plan again:
/plan On the home page add tabs For You and Following.
For You uses recommend from @lib/recommend.ts, Following shows
texts of followed authors, newest first. Next to the list a panel
with topics. Tab type as in PublicationTabs, no as any.Read the plan the way you did today: do the tabs have a type, do the lists have keys from the data, and does sorting work on a copy. In the editor below waits a publication page in miniature: switch the role, try to publish a text with the agent's bug "lock only in the button" switched on, and check the recommendation scores.
Remember: a fleet sails safely when only the captain and the officers hold the keys to the helm room, and the lock hangs on the door of the helm room, not on the map that anyone can redraw.
Code for this lesson: App.jsx
// A publication in miniature: roles, tabs, a lock on a fake server and a recommendation score
import { useState } from 'react';
const MEMBERS = [
{ userId: 'u-anne', name: 'Anne Bonny', role: 'owner' },
{ userId: 'u-bill', name: 'Billy Bones', role: 'editor' },
{ userId: 'u-jack', name: 'Calico Jack', role: 'writer' },
];
const ROLE_LABELS = { owner: 'owner', editor: 'editor', writer: 'writer' };
const TABS = [
{ key: 'latest', label: 'Latest' },
{ key: 'top', label: 'Top' },
{ key: 'about', label: 'About us' },
];
const ARTICLES = [
{ id: 'a1', publication: 'chronicles', title: 'How to Survive a Storm on the Atlantic', authorId: 'u-anne', topics: ['sailing', 'weather'], claps: 120, publishedAt: '2026-11-10' },
{ id: 'a2', publication: 'chronicles', title: 'The Treasure Map That Never Was', authorId: 'u-jack', topics: ['treasure'], claps: 340, publishedAt: '2026-11-12' },
{ id: 'a3', publication: 'galley', title: "The Ship's Cook Advises: Hardtack for Six Weeks", authorId: 'u-mary', topics: ['cooking', 'sailing'], claps: 45, publishedAt: '2026-11-14' },
{ id: 'a4', publication: 'chronicles', title: 'Night Watch Without Coffee', authorId: 'u-jack', topics: ['sailing'], claps: 0, publishedAt: '2026-11-15' },
];
const AUTHORS = { 'u-anne': 'Anne Bonny', 'u-jack': 'Calico Jack', 'u-mary': 'Mary Read' };
const TOPICS = ['sailing', 'weather', 'treasure', 'cooking'];
// The owner and the editor publish. The writer only submits a text.
function canPublish(role) {
return role === 'owner' || role === 'editor';
}
function roleOf(userId) {
const member = MEMBERS.find((m) => m.userId === userId);
return member ? member.role : undefined;
}
// A fake server: the route POST /api/articles/a4/publish
function publishOnServer(userId, lockOnlyInButton) {
if (!lockOnlyInButton && !canPublish(roleOf(userId))) return 403;
return 200;
}
// 3 for a followed topic, 2 for a followed author, 1 for every full 100 claps (at most 3)
function score(article, reader, noCap) {
const topics = article.topics.filter((t) => reader.topics.includes(t)).length;
const author = reader.authors.includes(article.authorId) ? 1 : 0;
const clapPoints = noCap ? Math.floor(article.claps / 10) : Math.min(3, Math.floor(article.claps / 100));
return 3 * topics + 2 * author + clapPoints;
}
export default function App() {
const [userId, setUserId] = useState('u-jack');
const [tab, setTab] = useState('latest');
const [publishedIds, setPublishedIds] = useState(['a1', 'a2', 'a3']);
const [lockOnlyInButton, setLockOnlyInButton] = useState(false);
const [log, setLog] = useState('');
const [reader, setReader] = useState({ topics: ['sailing'], authors: ['u-mary'] });
const [noCap, setNoCap] = useState(false);
const role = roleOf(userId);
const published = ARTICLES.filter((a) => publishedIds.includes(a.id));
const submitted = ARTICLES.filter((a) => a.id === 'a4' && !publishedIds.includes(a.id));
const mine = published.filter((a) => a.publication === 'chronicles');
const sorted =
tab === 'top'
? [...mine].sort((a, b) => b.claps - a.claps)
: [...mine].sort((a, b) => b.publishedAt.localeCompare(a.publishedAt));
const recommended = [...published]
.map((a) => ({ article: a, points: score(a, reader, noCap) }))
.sort((a, b) => b.points - a.points || b.article.publishedAt.localeCompare(a.article.publishedAt));
function publish(source) {
const status = publishOnServer(userId, lockOnlyInButton);
setLog(source + ': the server answered ' + status);
if (status === 200) setPublishedIds((ids) => (ids.includes('a4') ? ids : [...ids, 'a4']));
}
function toggle(list, value) {
return list.includes(value) ? list.filter((v) => v !== value) : [...list, value];
}
return (
<div className="min-h-screen bg-gray-50 p-4 text-gray-900">
<div className="mx-auto max-w-xl space-y-4 rounded-xl bg-white p-4 shadow-sm">
<label className="block text-sm">
Logged in as (fake demo-user cookie):{' '}
<select value={userId} onChange={(e) => setUserId(e.target.value)} className="rounded border border-gray-300">
{MEMBERS.map((m) => (
<option key={m.userId} value={m.userId}>{m.name} ({ROLE_LABELS[m.role]})</option>
))}
<option value="u-guest">Guest from outside the crew</option>
</select>
</label>
<header>
<h1 className="text-2xl font-bold">Chronicles of the Cape</h1>
<p className="text-gray-600">{(12480).toLocaleString('en-US')} followers</p>
</header>
<div role="tablist" className="flex gap-4 border-b border-gray-200">
{TABS.map((t) => (
<button
key={t.key}
type="button"
role="tab"
aria-selected={tab === t.key}
onClick={() => setTab(t.key)}
className={tab === t.key ? 'border-b-2 border-gray-900 pb-2 font-semibold' : 'pb-2 text-gray-500'}
>
{t.label}
</button>
))}
</div>
{tab === 'about' ? (
<ul>
{MEMBERS.map((m) => (
<li key={m.userId}>{m.name}: {ROLE_LABELS[m.role]}</li>
))}
</ul>
) : (
<ul className="space-y-2">
{sorted.map((article) => (
<li key={article.id}>
<p className="font-semibold">{article.title}</p>
<p className="text-sm text-gray-500">{article.claps} claps ยท {article.publishedAt}</p>
</li>
))}
</ul>
)}
{submitted.length > 0 && canPublish(role) && (
<div className="rounded bg-amber-50 p-2 text-sm">
Submitted: {submitted[0].title}{' '}
<button type="button" onClick={() => publish('Button')} className="rounded bg-gray-900 px-2 py-1 text-white">
Publish
</button>
</div>
)}
</div>
<div className="mx-auto mt-3 max-w-xl space-y-2 rounded-xl bg-gray-900 p-4 text-sm text-white">
<button type="button" onClick={() => publish('Request bypassing the button')} className="rounded bg-gray-700 px-3 py-1">
Send POST /api/articles/a4/publish (like curl)
</button>
{log && <p className="text-amber-300">{log}</p>}
<label className="flex items-center gap-2">
<input type="checkbox" checked={lockOnlyInButton} onChange={(e) => setLockOnlyInButton(e.target.checked)} />
Agent's bug: the lock only in the button
</label>
</div>
<div className="mx-auto mt-3 max-w-xl space-y-2 rounded-xl bg-white p-4 text-sm shadow-sm">
<p className="font-semibold">For You: recommendation points</p>
<div className="flex flex-wrap gap-3">
{TOPICS.map((t) => (
<label key={t} className="flex items-center gap-1">
<input type="checkbox" checked={reader.topics.includes(t)} onChange={() => setReader((r) => ({ ...r, topics: toggle(r.topics, t) }))} />
{t}
</label>
))}
<label className="flex items-center gap-1">
<input type="checkbox" checked={reader.authors.includes('u-mary')} onChange={() => setReader((r) => ({ ...r, authors: toggle(r.authors, 'u-mary') }))} />
I follow Mary Read
</label>
</div>
<ol className="list-decimal pl-5">
{recommended.map(({ article, points }) => (
<li key={article.id}>
{article.title} ({AUTHORS[article.authorId]}): <strong>{points} pts</strong>
</li>
))}
</ol>
<label className="flex items-center gap-2">
<input type="checkbox" checked={noCap} onChange={(e) => setNoCap(e.target.checked)} />
No cap: 1 point for every 10 claps
</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. What do you give Claude as a sketch of the publication page?
2. Why does the request tell Claude to first describe the sketch in a few sentences and only then plan?
These are 2 of 10 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Put in order the way of a writer's text to the Latest tab:
- Code editor
Publication display
- Click in order
Click the elements to build the points for claps with an upper bound of 3:
- Code editor
Feed interface
- Vertical ordering
Put in order the lines of the tab definition from which TypeScript pulls the TabKey type:
- Horizontal ordering
Put in order, in one line, the handling of a tab click with the TabKey type:
- Vertical ordering
Put the roles in a publication in order from the widest to the narrowest permissions:
- Horizontal ordering
Put in order, in one line, the reading of a person's role in the publication route:
- Click in order
Click the elements to build the Top list without changing the array from props:
- Vertical ordering
Put the lines of the publication route in order from reading the parameters to saving:
- Horizontal ordering
Put in order, in one line, the header of a POST route with the parameters as a promise:
Tasks after this lesson
- QuestionA sketch of the publication page
- QuestionDescribing the sketch before the plan
- Put in orderA text's way to publication
- Coding taskPractice: Publication page
- QuestionA score you can explain
- QuestionThe points of one article
- Click in orderClap points with a cap
- Coding taskPractice: Home feed
- QuestionWho publishes in a publication
- QuestionA lock only in the button
- Put in orderTabs with a type
- Put in orderA tab click without casting
- QuestionA tab type error and as any
- QuestionA list item key
- Put in orderRoles from the widest permissions
- Put in orderA role from the cookie on the server
- Click in orderTop from a copy of the list
- QuestionThe cap on clap points
- Put in orderThe order in the publication route
- Put in orderThe POST route header
- QuestionThe route says 200, the page is unchanged