Vibe coding with Claude Code course · Module 8: Slack clone
Ship's Cabins: Ship's Comms Channels and the Formatting Hook
In this lesson17
Ahoy! On a big ship orders pass from mouth to mouth, and half of them die before they reach the hold. In this location you build Ship's Comms, a Slack-style messenger for the crew. In Kraken's Call, the Twitter clone, everyone saw every post. Here the conversation happens in a closed workspace of one crew, divided into channels, which are themed cabins.
What you will learn
- ask Claude Code for a data model, a sidebar and a separate address for every channel;
- check that a private channel is locked on the server, not just hidden in the menu;
- add a
PostToolUsehook that formats only the changed file after every edit; - read the
hookssection of.claude/settings.jsonand check it with the/hookscommand.
A new port: the ships-comms project
The messenger is a separate app, so you create it with the command from lesson 1_2, changing only the name. Before you click Yes, compare the command with this one:
npx create-next-app@latest ships-comms --ts --eslint --tailwind --app --no-src-dir --no-cache-components --agents-md --no-agent-feedback --use-npmThen comes the familiar routine: a session in the ships-comms folder, a CLAUDE.md that imports @AGENTS.md, Vitest with the @types/node fix from lesson 4_1, and a first commit. One thing is new: Prettier, a program that lays out code by fixed rules (indentation, quotes, breaking overly long lines). The Prettier documentation tells you to install it in the project with an exact version, because every release formats a little differently. Claude does this with npm install --save-dev --save-exact prettier, adds an empty .prettierrc file and writes one line into CLAUDE.md:
- Formatting: after every file change run npx prettier --write <file>Remember it, because at the end of the lesson we will check how much it is worth.
The problem: orders get lost in the crowd
The captain wants to announce the departure to the whole crew, the navigator wants to discuss the map with two people, and the merchant from Tortuga, a guest on board, should see only the trade talks. You need a sidebar with a list of channels and a separate address for every channel. The most important part is invisible: who sees which channel. A private channel hidden in the menu but open at its address is a lock on the door made of paper.
Request for Claude Code:
/plan Build a crew workspace in Ship's Comms. First the data model
in types/chat.ts: a crew member (handle, name, role
owner/admin/member/guest, presence online/away/offline), a channel
(public or private, list of members) and a private conversation
between two people. A channel does not hold messages. Test data in
lib/workspace.ts, the logged-in member from one function in
lib/session.ts. The visibility rule in a pure function canSeeChannel,
tests first: a private channel is visible only to its members, a
guest only sees the channels they were added to. Then a sidebar in
app/layout.tsx (workspace name, number of people online, channels,
direct messages with a presence dot, profile at the bottom) and a
/c/[channel] route with a channel header. A channel the member may
not see answers 404. At the end tests, lint, types and build.In the plan you look for two things: whether canSeeChannel guards both the list in the sidebar and the route itself, and whether the channel really has no field with messages. Messages will arrive in the next lesson as a separate list, like a separate table in a database.
What Claude wrote: the data model
Open types/chat.ts in Cursor. Roles and presence are unions, closed lists of values, so a typo such as "onlnie" will not get past the compiler:
export type Role = "owner" | "admin" | "member" | "guest";
export type Presence = "online" | "away" | "offline";
export interface Channel {
id: string;
name: string; // "general", "treasure-hunts"
topic: string;
isPrivate: boolean;
memberIds: string[];
}A channel keeps only the identifiers of its members, not copies of them, so changing a pirate's name does not require fixing five channels. The same file holds Member with a handle field, a short name for mentions such as redbeard, and DirectMessage, whose memberIds has the type [string, string]. That is a tuple, an array of exactly two elements, because a private conversation joins two people.
Who enters which cabin
Open lib/workspace.ts. The whole visibility rule fits in one function:
export function canSeeChannel(channel: Channel, member: Member): boolean {
if (channel.isPrivate || member.role === "guest") {
return channel.memberIds.includes(member.id);
}
return true;
}Every crew member sees a public channel, even before joining it. A private channel, and every channel viewed by a guest, requires being on the member list. The function knows nothing about React, so Claude first wrote three tests for it in lib/workspace.test.ts, and the sidebar and the channel page call the same function.
The channel route
Open app/c/[channel]/page.tsx. Square brackets in a folder name make it a dynamic route, and since Next.js 16 params is a promise (Promise), so the page waits for it with await:
const { channel: name } = await params;
const me = await getCurrentMember();
const channel = findChannel(name);
if (!channel || !canSeeChannel(channel, me)) {
notFound();
}notFound() from next/navigation stops rendering and shows the 404 page. A guest who types the address /c/captains-secrets gets the same message as for a channel that does not exist, so they will not even learn that such a cabin exists. getCurrentMember() stands in for login for now: it returns a fixed crew member and calls connection() so the page renders on every request, as it would with a real session.
The sidebar and the active channel
The sidebar in components/Sidebar.tsx is a Server Component: it reads the data, passes the channels through canSeeChannel and counts the people online. Highlighting the channel you are reading needs the address from the browser, though, so Claude split out a small Client Component, components/ChannelLink.tsx (classes omitted):
const pathname = usePathname();
const active = pathname === `/c/${name}`;
return (
<Link href={`/c/${name}`} aria-current={active ? "page" : undefined}>
<ChannelMark isPrivate={isPrivate} />
{name}
</Link>
);usePathname from next/navigation returns the path without query parameters; the Next.js documentation says outright that a Server Component cannot read the address. aria-current="page" tells a screen reader which link leads to the current page. ChannelMark draws a # for a public channel and a small SVG padlock for a private one, with a hidden label "private channel". The presence dot next to direct messages is green, yellow or gray, and beside it sits hidden text such as "(be right back)", because a screen reader cannot read a colour alone, and neither can someone who cannot tell green from yellow.
The channel header
components/ChannelHeader.tsx shows the name with a # or a padlock, the description and the number of members, and for a channel without a description the text "This channel has no description yet". The "+ Add people" button is visible only to the owner and admin roles. For now it does nothing, and when invitations arrive the server will check the permission: a hidden button is a courtesy, not a lock.
Captain's review
- A lock on the server, not in the menu. Change the logged-in member in
lib/session.tsto the guestmerchantand open/c/captains-secretsand/c/treasure-hunts. For us both pages answered 404, and the sidebar showed onlygeneralandtrade. A typical agent mistake: a filter only in the sidebar, while the channel page renders for anyone who knows the address. - A number with the right word. The first version of the sidebar wrote "1 people online". English needs one form for 1 and another for the rest, so Claude added
formatPeoplewithIntl.PluralRules("en-US")and a test: 1 person, 2 people, 5 people, 22 people. - Borders and colours. Every border gets a colour (
border-gray-200), because in Tailwind 4 a barebordertakes the text colour. Claude also removed fromapp/globals.cssthe dark theme block from the generator, which overrode thebodycolours. - Proof. Tests,
npm run lint,npx tsc --noEmitandnpm run build. Before the first buildtscdoes not know the typePageProps<"/c/[channel]">, because route types are generated bynext buildornext dev.
Formatting drifts
After a few fixes ask Claude: "Run npx prettier --check .". That command changes nothing, it only reports. For us it came out like this:
Checking formatting...
[warn] components/ChannelHeader.tsx
[warn] lib/workspace.ts
[warn] Code style issues found in 2 files. Run Prettier with --write to fix.In lib/workspace.ts a new channel sits on one long line with single quotes, and in the header a semicolon went missing. The code works, but the diff swells with changes that mean nothing, even though CLAUDE.md asks for Prettier after every change. You remember from lesson 1_7: the model reads CLAUDE.md and decides for itself what to do with it. It usually listens, but not always.
A hook: an order that is carried out every time
A hook is a command run by the Claude Code program itself at a given moment of the work, not by the model. The documentation calls this deterministic control: certain things happen every time, instead of depending on whether the model decides to do them. Such a moment is an event. PostToolUse fires right after a Claude tool finishes successfully, for example Edit (changing a fragment of a file) or Write (saving a whole file).
Request for Claude Code:
Add a PostToolUse hook to the project's .claude/settings.json that,
after every Edit and Write, formats only the edited file with the
project's Prettier. Take the path from the hook input
(tool_input.file_path), do not format the whole repository. Before
you save it, test the command by hand: give it a sample JSON on
input and show the result.What Claude wrote: the hooks section
Open .claude/settings.json in Cursor:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\""
}
]
}
]
}
}Read it from the outside in. The hooks key collects all hooks, below it stands the event name, and inside is a group with a matcher, which is a filter. For PostToolUse the matcher compares the tool name, and Edit|Write means "Edit or Write". Without it the hook would fire after every tool, Read included. Deepest lies the handler itself: the type command and a shell command. This is the example straight from the hooks documentation.
How the hook gets the file path
Claude Code passes the event data to the hook as JSON on standard input, that is stdin. For Edit and Write the field tool_input.file_path holds the full path of the changed file. jq is a small tool for reading JSON in the terminal: jq -r '.tool_input.file_path' extracts the path as plain text, and f=$(...) stores it in a variable. After && Prettier formats exactly that one file, and --ignore-unknown skips files it cannot format. Check that you have jq: jq --version. If the command is missing, the documentation gives brew install jq on macOS and apt-get install jq on Debian and Ubuntu.
A manual check
The documentation advises testing a hook by piping a sample JSON into it. Claude did it on a file that was badly formatted a moment ago:
echo '{"tool_input":{"file_path":"lib/workspace.ts"}}' | (f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown "$f"); echo "exit code: $?"The result:
lib/workspace.ts 34ms
exit code: 0Prettier fixed one file, and npx prettier --check . again ended with "All matched files use Prettier code style!". Code 0 means success. Claude also tried a path with a folder that has a space in its name. With the quotes around "$f" it worked, and without them Prettier answered "No files matching the pattern were found" with code 2, because the shell chopped the path into two pieces.
/hooks and a live test
Type /hooks in the session. According to the documentation it is a read-only hook browser: a list grouped by events, with each hook's source next to it, for example the project settings, and the full command once you select one. Your hook should stand under PostToolUse. Claude Code usually notices a change in the settings file by itself; if the hook is not on the list, start the session again.
Now the test from the documentation: ask Claude to add to any TypeScript file a line with text in single quotes, then open that file. The hook turned them into double quotes. In the conversation you will see nothing, because a successful hook is silent; its trace shows in the file or in the transcript view under Ctrl+O.
Two limits from the documentation. A hook with the matcher Edit|Write will not fire when a file is changed by a Bash command, such as sed. And the hook command runs with your permissions, so you read every hook like any other command, especially in somebody else's repository.
A hook or a line in CLAUDE.md
A line in CLAUDE.md is a request: the model usually listens, but it may skip it when the conversation is long or the task is urgent. A hook is ship's law enforced by the program itself: it runs after every edit, whether Claude remembers it or not. I recommend a simple rule: what should happen every time and can be checked by a machine, like formatting, hand to a hook, and leave the guidance that needs judgment in CLAUDE.md. You can now remove the Prettier line from CLAUDE.md.
Next step
Ask for a commit, for example "Channels, sidebar and the formatting hook". .claude/settings.json travels in the repository with the code, so everyone who clones the project gets the hook. Then a small step with the same lock rule:
Add a /dm/[id] route for private conversations. Only the two
people in memberIds may open it, everyone else gets 404. Tests of
the function canSeeDirectMessage first. At the end tests, lint,
types and build.In the diff you will see new files already formatted, although the request never mentioned Prettier.
The editor below holds a workspace in miniature: switch to the guest and open a private channel by its address, and in the Hook tab check for which tools the matcher fires.
Remember: a channel is a cabin with a list of those who may enter, and a hook is the watch officer who checks after every change that the deck is scrubbed.
Code for this lesson: App.jsx
// Ship's Comms in miniature: channels, the visibility rule and the hook matcher.
// In the project the rule is enforced by canSeeChannel on the server (the channel page returns 404),
// and the formatting hook lives in .claude/settings.json. Here both run in the browser.
import { useState } from 'react';
const members = [
{ id: 'u1', handle: 'redbeard', name: 'Captain Redbeard', role: 'owner', presence: 'online', statusText: 'On the bridge' },
{ id: 'u2', handle: 'anne', name: 'Anne Bonny', role: 'admin', presence: 'online' },
{ id: 'u3', handle: 'łukasz', name: 'Łukasz Sternik', role: 'member', presence: 'away', statusText: 'At the helm' },
{ id: 'u4', handle: 'jack', name: 'Jack Rackham', role: 'member', presence: 'offline' },
{ id: 'u5', handle: 'merchant', name: 'Merchant from Tortuga', role: 'guest', presence: 'online' },
];
const channels = [
{ id: 'c1', name: 'general', topic: 'Announcements for the whole crew', isPrivate: false, memberIds: ['u1', 'u2', 'u3', 'u4', 'u5'] },
{ id: 'c2', name: 'treasure-hunts', topic: 'Planning treasure expeditions', isPrivate: false, memberIds: ['u1', 'u2', 'u3', 'u4'] },
{ id: 'c4', name: 'trade', topic: 'Talks with merchants', isPrivate: false, memberIds: ['u1', 'u2', 'u5'] },
{ id: 'c5', name: 'captains-secrets', topic: '', isPrivate: true, memberIds: ['u1', 'u2'] },
];
const directMessages = [
{ id: 'd1', memberIds: ['u1', 'u2'] },
{ id: 'd2', memberIds: ['u1', 'u3'] },
{ id: 'd3', memberIds: ['u1', 'u5'] },
{ id: 'd4', memberIds: ['u2', 'u4'] },
];
// The same function as in lib/workspace.ts.
function canSeeChannel(channel, member) {
if (channel.isPrivate || member.role === 'guest') {
return channel.memberIds.includes(member.id);
}
return true;
}
const plural = new Intl.PluralRules('en-US');
const peopleWords = { one: 'person', other: 'people' };
function formatPeople(count) {
return count + ' ' + peopleWords[plural.select(count)];
}
const dotColors = { online: 'bg-green-500', away: 'bg-yellow-400', offline: 'bg-gray-400' };
const dotLabels = { online: 'available', away: 'be right back', offline: 'unavailable' };
function PresenceDot({ presence }) {
return (
<>
<span aria-hidden="true" className={'inline-block h-2.5 w-2.5 shrink-0 rounded-full ' + dotColors[presence]} />
<span className="sr-only">({dotLabels[presence]})</span>
</>
);
}
function ChannelMark({ isPrivate }) {
if (!isPrivate) return <span aria-hidden="true">#</span>;
return (
<>
<svg aria-hidden="true" viewBox="0 0 16 16" className="h-3.5 w-3.5 fill-current">
<path d="M4 7V5a4 4 0 1 1 8 0v2h1v8H3V7h1Zm2 0h4V5a2 2 0 1 0-4 0v2Z" />
</svg>
<span className="sr-only">private channel</span>
</>
);
}
// Matcher "Edit|Write": a list of exact tool names separated by |.
function matches(matcher, toolName) {
return matcher.split('|').map((part) => part.trim()).includes(toolName);
}
function HookLab() {
const [tool, setTool] = useState('Edit');
const [path, setPath] = useState('/Users/you/ships-comms/lib/workspace.ts');
const input = { hook_event_name: 'PostToolUse', tool_name: tool, tool_input: { file_path: path } };
const runs = matches('Edit|Write', tool);
return (
<section className="space-y-3 rounded-lg border border-gray-200 bg-white p-4">
<h2 className="font-bold">PostToolUse hook with the Edit|Write matcher</h2>
<div className="flex flex-wrap gap-2">
{['Edit', 'Write', 'Read', 'Bash'].map((name) => (
<button
key={name}
onClick={() => setTool(name)}
aria-pressed={tool === name}
className={'rounded-full border px-3 py-1 text-sm ' + (tool === name ? 'border-blue-600 bg-blue-50 font-semibold' : 'border-gray-300')}
>
{name}
</button>
))}
</div>
<label className="block text-sm">
File path in tool_input.file_path
<input value={path} onChange={(e) => setPath(e.target.value)} className="mt-1 w-full rounded-md border border-gray-300 px-2 py-1 font-mono text-xs" />
</label>
<p className="text-xs text-gray-500">This is the JSON the hook receives on standard input:</p>
<pre className="overflow-x-auto rounded-md bg-gray-900 p-3 text-xs text-green-200">{JSON.stringify(input, null, 2)}</pre>
{runs ? (
<p className="rounded-md bg-green-50 p-2 text-sm text-green-800">
The hook runs and formats one file: npx prettier --write --ignore-unknown "{path}"
</p>
) : (
<p className="rounded-md bg-gray-100 p-2 text-sm text-gray-700">
The Edit|Write matcher does not match {tool}: the hook stays silent.
</p>
)}
</section>
);
}
export default function App() {
const [meId, setMeId] = useState('u1');
const [address, setAddress] = useState('/c/general');
const [draft, setDraft] = useState('/c/general');
const [tab, setTab] = useState('channels');
const me = members.find((m) => m.id === meId);
const visible = channels.filter((channel) => canSeeChannel(channel, me));
const online = members.filter((m) => m.presence === 'online').length;
const partners = directMessages
.filter((dm) => dm.memberIds.includes(me.id))
.map((dm) => members.find((m) => m.id === dm.memberIds.find((id) => id !== me.id)));
const name = address.startsWith('/c/') ? address.slice(3) : '';
const channel = channels.find((c) => c.name === name);
const allowed = channel && canSeeChannel(channel, me);
const canInvite = me.role === 'owner' || me.role === 'admin';
function open(path) {
setAddress(path);
setDraft(path);
}
return (
<div className="min-h-screen bg-gray-100 p-3 text-gray-900">
<div className="mb-3 flex flex-wrap items-center gap-2 text-sm">
<label htmlFor="me">Logged in as:</label>
<select id="me" value={meId} onChange={(e) => setMeId(e.target.value)} className="rounded-md border border-gray-300 bg-white px-2 py-1">
{members.map((m) => (
<option key={m.id} value={m.id}>{m.name} ({m.role})</option>
))}
</select>
<button onClick={() => setTab('channels')} className={'rounded-md px-3 py-1 ' + (tab === 'channels' ? 'bg-purple-900 text-white' : 'bg-white')}>Channels</button>
<button onClick={() => setTab('hook')} className={'rounded-md px-3 py-1 ' + (tab === 'hook' ? 'bg-purple-900 text-white' : 'bg-white')}>Hook</button>
</div>
{tab === 'hook' ? (
<HookLab />
) : (
<div className="flex min-h-96 overflow-hidden rounded-lg border border-gray-200 bg-white">
<aside className="flex w-52 shrink-0 flex-col bg-purple-900 text-white">
<div className="border-b border-purple-800 p-3">
<p className="font-bold">Black Pearl Crew</p>
<p className="text-xs text-purple-200">{formatPeople(online)} online</p>
</div>
<nav aria-label="Channels" className="flex-1 p-2 text-sm">
<p className="px-2 py-1 text-xs font-semibold uppercase text-purple-300">Channels</p>
<ul>
{visible.map((c) => {
const active = address === '/c/' + c.name;
return (
<li key={c.id}>
<button
onClick={() => open('/c/' + c.name)}
aria-current={active ? 'page' : undefined}
className={'flex w-full items-center gap-2 rounded-md px-2 py-1 text-left ' + (active ? 'bg-blue-600 font-semibold' : 'hover:bg-purple-800')}
>
<ChannelMark isPrivate={c.isPrivate} />
{c.name}
</button>
</li>
);
})}
</ul>
<p className="mt-3 px-2 py-1 text-xs font-semibold uppercase text-purple-300">Direct messages</p>
<ul>
{partners.map((m) => (
<li key={m.id} className="flex items-center gap-2 px-2 py-1">
<PresenceDot presence={m.presence} />
{m.name}
</li>
))}
</ul>
</nav>
<div className="flex items-center gap-2 border-t border-purple-800 p-2 text-xs">
<PresenceDot presence={me.presence} />
<span className="truncate">{me.name}: {me.statusText ?? 'On deck'}</span>
</div>
</aside>
<main className="flex min-w-0 flex-1 flex-col">
<form
onSubmit={(e) => {
e.preventDefault();
open(draft.trim());
}}
className="flex gap-2 border-b border-gray-200 p-2"
>
<label htmlFor="address" className="sr-only">Address</label>
<input id="address" value={draft} onChange={(e) => setDraft(e.target.value)} className="min-w-0 flex-1 rounded-md border border-gray-300 px-2 py-1 font-mono text-sm" />
<button className="rounded-md bg-gray-800 px-3 text-sm text-white">Open</button>
</form>
{allowed ? (
<header className="flex items-center justify-between gap-3 border-b border-gray-200 px-4 py-3">
<div className="min-w-0">
<h1 className="flex items-center gap-1 text-lg font-bold">
<ChannelMark isPrivate={channel.isPrivate} />
{channel.name}
</h1>
<p className="truncate text-sm text-gray-600">
{channel.topic || 'This channel has no description yet'} · {formatPeople(channel.memberIds.length)}
</p>
</div>
{canInvite && (
<button className="shrink-0 rounded-md border border-gray-300 px-3 py-1 text-sm font-semibold">+ Add people</button>
)}
</header>
) : (
<div className="p-6">
<h1 className="text-2xl font-bold">404</h1>
<p className="text-gray-600">There is no such page. A channel that does not exist and a channel you may not see get the same message.</p>
</div>
)}
<p className="p-4 text-sm text-gray-500">Try opening /c/captains-secrets or /c/treasure-hunts as a guest.</p>
</main>
</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. Why does the Channel type in Ship's Comms hold only memberIds, and not copies of members or a list of messages?
2. How does a public channel differ from a private one in Ship's Comms?
These are 2 of 7 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Slack workspace navigation
- Click in order
Arrange the line the channel page uses to read the name from the address: const { channel: name } = await params;
- Click in order
Arrange the header of the captains-secrets channel (private, no description, 2 members) in display order. Click only the elements you need:
- Vertical ordering
Order what happens when a guest types the address /c/captains-secrets:
- Code editor
Channel header component
- Horizontal ordering
Arrange on one line the beginning of the function: export function canSeeChannel(channel: Channel, member: Member): boolean {
- Vertical ordering
Arrange the sections of the Ship's Comms sidebar from top to bottom:
- Click in order
Arrange the command of the hook that formats only the edited file:
Tasks after this lesson
- QuestionQuiz: A channel without copied data
- QuestionQuiz: Public and private channel
- QuestionQuiz: The guest role
- Coding taskPractice: Workspace sidebar
- QuestionQuiz: Crew member presence
- QuestionQuiz: Text next to the presence dot
- Click in orderSorting: Channel name from params
- Click in orderSorting: Private channel header
- Put in orderSorting: A guest at a private channel address
- Coding taskPractice: Channel header
- QuestionQuiz: Fields of the Channel type
- Put in orderSorting: The canSeeChannel signature
- Put in orderSorting: Sidebar sections
- QuestionQuiz: The tuple in DirectMessage
- Click in orderSorting: The Prettier hook command