Vibe coding with Claude Code course Β· Module 7: LinkedIn clone
A rope between ships: live chat and a server in the background
In this lesson9
A recruiter from the Black Pearl writes to Anne Bonny: "Do you have time to talk about the officer position?". Anne has the page open, but nothing happens until she refreshes it. In lesson 5_5 the bell asked the server every 30 seconds. In a conversation that is an eternity, and most of those questions come back empty. You need a rope stretched between ships: a connection through which the server itself sends a message as soon as it appears.
Server-Sent Events: a one-way rope
Server-Sent Events (SSE) is a permanent HTTP connection through which the server sends the browser a series of events in the text/event-stream format. The browser listens through the built-in EventSource object. Unlike a WebSocket, this rope works in one direction only, from the server to the browser. For a chat that is enough: you send a message with an ordinary POST request, and the stream only carries it to the open tabs. You need no separate server and no library, because the Next.js documentation names a Route Handler as the place for an SSE stream.
This is several files and a new kind of connection, so you start with a plan, and you order the check right away:
Request for Claude Code:
/plan Add a 1-to-1 chat: a page /messages/[handle], and the Message
button on a contact card leads to the conversation. New messages
arrive without a refresh through Server-Sent Events: a Route Handler
app/api/messages/[handle]/route.ts, GET returns a text/event-stream
stream, POST accepts { content } as JSON. The server sets the sender
from getCurrentUser(). Save through lib/store.ts, the page shows the
history. No new libraries, tests for the pure functions.
Then start the dev server in the background and test the chat
yourself: a curl listening to the stream and a second curl with POST.
Show me what the first one received.In the plan you look for three things: the sender taken from the session and not from the request body, cleanup of the connection on both sides, and the check Claude will run before it hands the work over.
What Claude wrote: an event in the stream
Open lib/chat.ts in Cursor. The ChatMessage type from types/message.ts has id, from, to, the content and sentAt, and an SSE event is a few lines of text ended by an empty line:
// The same conversation for both sides: "anne:redbeard", whoever writes.
export function conversationId(a: string, b: string): string {
return [a, b].sort().join(":");
}
export function toEvent(message: ChatMessage): string {
return `id: ${message.id}\ndata: ${JSON.stringify(message)}\n\n`;
}conversationId sorts the two handles, so the conversation of redbeard with Anne and of Anne with redbeard has one identifier. The empty line at the end of the event is not decoration: only it tells the browser that the message is complete. JSON.stringify turns a newline in the content into \n, so a message with two paragraphs fits in a single data line. Tests in lib/chat.test.ts guard both things.
What Claude wrote: the stream on the server
lib/chat-hub.ts keeps in memory a map of conversations and their listeners, that is, functions that append a message to an open stream. subscribe adds a listener and returns a function that removes it, and publish calls all the listeners of one conversation. The answer to GET in app/api/messages/[handle]/route.ts is a ReadableStream, a Web API stream that hands out the response in pieces:
const stream = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(encoder.encode(": connected\n\n"));
unsubscribe = subscribe(conversationId(user.handle, partner.handle), (message) => {
controller.enqueue(encoder.encode(toEvent(message)));
});
},
cancel() {
unsubscribe(); // the tab is closed: stop sending to this stream
},
});
return new Response(stream, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } });start runs once, when the stream opens, and controller.enqueue pushes out the next piece. encoder is the built-in TextEncoder, which turns text into bytes, because a stream carries bytes. cancel arrives when the browser disconnects. A line that starts with a colon is a comment the browser skips; what it is for here you will see in the review. The conversation is determined by the logged-in pirate and the handle from the address, so nobody can eavesdrop on someone else's conversation by typing its name into a parameter.
What Claude wrote: sending
POST in the same file checks the content with a Zod schema (from 1 to 1000 characters after trim()) and builds the rest of the message itself:
const message: ChatMessage = {
id: randomUUID(),
from: user.handle,
to: partner.handle,
content: result.data.content,
sentAt: new Date().toISOString(),
};
await addMessage(message);addMessage from lib/messages.ts saves the message to data/messages.json and calls publish, so it reaches every open tab of that conversation, the sender's tab included. The form in ChatWindow therefore appends nothing by itself, it only waits for the message to come back through the stream. The server ignores a from field sent in the request.
What Claude wrote: the tab listens
Open components/messages/useChat.ts. The hook starts with the history the page read on the server and appends whatever arrives:
useEffect(() => {
const source = new EventSource(`/api/messages/${handle}`);
source.onopen = () => setConnected(true);
source.onerror = () => setConnected(false); // the browser will try to reconnect by itself
source.onmessage = (event) => {
const message: ChatMessage = JSON.parse(event.data);
setMessages((current) => [...current, message]);
};
return () => source.close();
}, [handle]);State changes only in callbacks, not in the body of the effect itself, so the react-hooks/set-state-in-effect rule passes. When the connection breaks, the browser reconnects by itself. source.close() coils the rope back when the tab switches conversation or disappears. The page renders ChatWindow with key={partner.handle}, so that moving to another conversation does not leave old messages in state.
A server in the background, Claude tests
After the build Claude runs npm run dev. A dev server never finishes by itself, so if Claude starts it with a plain command, the session stands and waits. Press Ctrl+B then: Claude Code moves the running command to the background (in tmux press it twice) and writes its output to a file that Claude reads when it needs to. You can also write "run it in the background" right away, as in the request. The documentation gives dev servers as a typical example of background work.
Now Claude has free hands. The first curl also runs forever, because it listens to the stream, so it goes to the background too, and the second one sends a message with a forged sender:
curl -N http://localhost:3000/api/messages/anne
curl -X POST http://localhost:3000/api/messages/anne -H "Content-Type: application/json" -d '{"content":"Ahoy, Anne!","from":"anne"}'The -N flag turns off curl's buffering so the events show up at once. The second curl gets status 201 and a message in which from is redbeard, although the request said anne. Claude reads the output file of the first:
: connected
id: e8705818-17b3-4c9b-80f9-68ec0fef6ff8
data: {"id":"e8705818-17b3-4c9b-80f9-68ec0fef6ff8","from":"redbeard","to":"anne","content":"Ahoy, Anne!","sentAt":"2026-11-14T18:46:35.931Z"}Type /tasks in the session: you will see the background work, that is the server and the listening curl, and you can stop either one there. This command works at once, even while Claude is still writing. Do not confuse it with Ctrl+T, which shows Claude's task list, not processes. Everything that runs in the background, Claude Code cleans up when you leave the session.
The last test is yours: on /network click Message at Anne Bonny and open the same address in a second tab. Write in the first one, and the message appears in both without a refresh, with the label "Live" above the conversation. There is no login yet, so both tabs are you; you will test a conversation of two people when the crew gets accounts.
Captain's review
- No cleanup in the browser. A typical agent mistake is an effect without
return () => source.close(). We checked: in development mode React deliberately runs the effect twice: it mounts, cleans up and mounts again (Strict Mode is on by default in the App Router), so two streams appeared, every message showed up twice, and the console reported "Encountered two children with the same key". In production the same mistake leaves a connection open after every move to another conversation. - No cleanup on the server. Remove
cancelas a test and close the conversation tab. In our run the next message got a 500 error, and the terminal showedTypeError: Invalid state: Controller is already closed:publishwas writing to a stream nobody was reading any more. The message had already been saved, so the sender saw an error for something that worked. - "Connecting..." forever. Without the
: connectedcomment at the start, the label above the conversation hung until someone wrote something. Next.js sent the headers only with the first piece of the response, soonopenwaited too. - State set in the body of an effect. When an agent puts
setConnected(false)at the start of the effect,npm run lintreportsreact-hooks/set-state-in-effect. The initial statefalse, changed only byonopenandonerror, is enough.
In production: Supabase Realtime
The map of listeners lives in the memory of one Node process. On a single server that works, but a host that runs several copies of the app has several separate maps: a message sent to one copy will not reach a tab connected to another. On top of that, without HTTP/2 a browser keeps at most 6 SSE connections to one domain, counting all tabs (MDN). Then, instead of your own map, you take a real-time service. We did not test this part in practice; these are facts from the Supabase documentation, as of November 2026:
- Supabase Realtime has three features: Broadcast (messages between clients, for example a chat), Presence (who is online) and Postgres Changes (listening to changes in tables). For most uses the documentation recommends Broadcast, and it describes Postgres Changes as good for tests and a small number of users.
- A client from the
@supabase/supabase-jspackage joins a channel, a named room, withconfig: { private: true }. In a React effect you clean it up withsupabase.removeChannel(channel): the same rule assource.close(). - Who may listen and send on a private channel is decided by Row Level Security (RLS) rules on the
realtime.messagestable. The documentation says to use only private channels in production. - The free plan allows 200 concurrent connections and 2 million messages a month.
Next step
When the review passes, ask for a commit, for example "Live chat with Server-Sent Events". We checked one more thing: after a server restart the browser reconnected by itself and sent the id of the last message back in the Last-Event-ID header. Messages from the gap are lost, though, so the next small step:
After a broken connection EventSource reconnects by itself and sends
the Last-Event-ID header. On the server, fetch the messages of this
conversation that came after that id before you start listening for
new ones. First a test of the pure function that selects them.In the editor below wait two tabs of the same conversation and a counter of open streams. Close the second tab and open it again, then turn "No cleanup" on and off, send a message and watch the counter grow and the messages double.
Remember: a rope between ships holds as long as both sides tend the knots, and whoever cast it off coils it back when they sail away.
Code for this lesson: App.jsx
// Live chat in miniature: two tabs of the same conversation and an in-memory "server".
// In the project the server is a Route Handler with text/event-stream, and the tab listens through EventSource.
// Here openStream pretends to be new EventSource(...), and sendToServer pretends to be POST /api/messages/anne.
import { useActionState, useEffect, useState, useSyncExternalStore } from 'react';
const ME = 'redbeard';
const saved = []; // saved messages, like data/messages.json
const streams = new Set(); // open streams, like the listeners in lib/chat-hub.ts
const watchers = new Set();
let nextId = 1;
const notify = () => watchers.forEach((watch) => watch());
function openStream() {
const source = {
onmessage: null,
close() {
streams.delete(source);
notify();
},
};
streams.add(source);
notify();
return source;
}
// The server assigns the id and the sender, saves the message and sends it to every open stream.
function sendToServer(content) {
const text = content.trim();
if (!text) return { ok: false, error: 'Write something before you send.' };
const message = { id: 'm' + nextId++, from: ME, to: 'anne', content: text };
setTimeout(() => {
saved.push(message);
streams.forEach((source) => source.onmessage?.({ data: JSON.stringify(message) }));
}, 200);
return { ok: true };
}
// React reads the count of open streams from a store outside the components.
function useOpenStreams() {
return useSyncExternalStore(
(watch) => {
watchers.add(watch);
return () => watchers.delete(watch);
},
() => streams.size
);
}
function useChat(leaky) {
const [messages, setMessages] = useState(() => [...saved]); // history, as if from the server
useEffect(() => {
const source = openStream();
source.onmessage = (event) => {
const message = JSON.parse(event.data);
setMessages((current) => [...current, message]);
};
if (leaky) return; // a typical agent mistake: no cleanup
return () => source.close();
}, [leaky]);
return messages;
}
function ChatWindow({ title, inputId, leaky }) {
const messages = useChat(leaky);
const [state, formAction, pending] = useActionState(
async (_prev, formData) => {
const content = String(formData.get('content') ?? '');
const result = sendToServer(content);
return result.ok ? { content: '', error: '' } : { content, error: result.error };
},
{ content: '', error: '' }
);
return (
<section className="flex h-80 flex-col rounded-lg border border-gray-200 bg-white">
<p className="border-b border-gray-200 px-3 py-2 text-xs font-semibold text-gray-500">{title}</p>
<ol className="flex-1 space-y-2 overflow-y-auto p-3">
{messages.map((message) => (
<li key={message.id} className="text-right">
<span className="inline-block rounded-2xl bg-blue-600 px-3 py-2 text-left text-sm text-white">{message.content}</span>
</li>
))}
</ol>
<form action={formAction} className="flex gap-2 border-t border-gray-200 p-2">
<label htmlFor={inputId} className="sr-only">Message</label>
<input
id={inputId}
name="content"
defaultValue={state.content}
autoComplete="off"
placeholder="Write a message"
className="min-w-0 flex-1 rounded-full border border-gray-300 px-3 py-1.5 text-sm"
/>
<button disabled={pending} className="rounded-full bg-blue-600 px-3 text-sm font-semibold text-white">
Send
</button>
</form>
{state.error && <p className="px-3 pb-2 text-xs text-red-600">{state.error}</p>}
</section>
);
}
export default function App() {
const [secondOpen, setSecondOpen] = useState(true);
const [leaky, setLeaky] = useState(false);
const open = useOpenStreams();
return (
<div className="min-h-screen bg-gray-100 p-4 text-gray-900">
<div className="mx-auto max-w-3xl space-y-3">
<div className="flex flex-wrap items-center gap-3 rounded-lg border border-gray-200 bg-white p-3 text-sm">
<span className="font-semibold">Open streams: {open}</span>
<button
onClick={() => setSecondOpen(!secondOpen)}
className="rounded-full border border-blue-600 px-3 py-1 font-semibold text-blue-700"
>
{secondOpen ? 'Close tab 2' : 'Open tab 2'}
</button>
<label className="flex items-center gap-2">
<input type="checkbox" checked={leaky} onChange={(e) => setLeaky(e.target.checked)} />
No cleanup (a typical mistake)
</label>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<ChatWindow title="Tab 1: conversation with Anne Bonny" inputId="message-1" leaky={leaky} />
{secondOpen && <ChatWindow title="Tab 2: the same conversation" inputId="message-2" leaky={leaky} />}
</div>
</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. How do Server-Sent Events differ from a WebSocket?
2. What does the tab do in source.onmessage when an event arrives from the stream?
Hands-on tasks in the game
- Click in order
Arrange opening the stream in useChat: new EventSource(
/api/messages/${handle}) - Vertical ordering
Order the path of a message from clicking Send to the second tab: