Vibe coding with Claude Code course · Module 8: Slack clone
A Report for the Ship Owner: a CSV Export That Will Not Fall Apart, and a PDF from Print
In this lesson8
The quartermaster wants the channel history in a spreadsheet, and the ship owner wants the dashboard report as a PDF. Both files have to come out right even when the crew writes commas, quotes and new lines, and even when someone malicious types into the chat a text that a spreadsheet takes for a formula.
The problem: text from people in a file for machines
CSV (comma-separated values) is plain text: one line is one record, and a comma separates cells. Chat messages break those rules at every step, because they contain commas and new lines themselves. The CSV standard, RFC 4180 (https://www.rfc-editor.org/rfc/rfc4180), says that a cell with a comma, a quote or a new line is wrapped in quotes, and a quote inside is doubled. The second danger has a name: formula injection (CSV Injection). A spreadsheet treats a cell starting with = as a formula, and the OWASP page "CSV Injection" (https://community.owasp.org/attacks/CSV_Injection) describes how such a formula can pull data out of an open spreadsheet or push someone to ignore a warning. The third matter is access: an export is only another road to the same messages, so the same rule guards it as the channel page.
Request for Claude Code:
Add an export of the channel history to CSV: a GET Route Handler at
/c/[channel]/export and an "Export CSV" link in the channel header.
A channel the logged-in member may not see answers 404.
First tests for the toCsv function in lib/csv.ts: a comma, a quote
and a new line in the text, an empty list, a missing value, a text
starting with =, +, - or @ (the rules from the OWASP page
"CSV Injection", give the link). Accented letters must work
in Excel. At the end tests, lint, types and build.What the first run showed
The first version of toCsv fit in one line: row.join(",") for every row and join("\n") for the whole. Five of six tests failed. To see what would land with the quartermaster, Claude ran two messages through the function: a shopping list with a comma, quotes and a second line, and a text starting with =. The result:
Date,Author,Text,Reactions
2026-11-14 09:00,Anne Bonny,For tomorrow: water, rum and "hardtack"
the rest in the hold,2
2026-11-14 09:05,Jack Rackham,=HYPERLINK("https://example.com";"Treasure map"),0A parser that follows the standard read four records from this instead of three. In Anne's row the "Text" column got only "For tomorrow: water", and the rest of the sentence landed in the "Reactions" column. The second line of the message became a separate record with two cells. Jack's text passed unchanged, so a spreadsheet would see a formula with a link in it.
What Claude wrote: a cell that will not fall apart
Open lib/csv.ts in Cursor. The Cell type describes the value of a cell: text, a number or no value. All the safety fits in one function:
const FORMULA_START = /^[=+\-@\t\r\n=+-@]/;
export function escapeCell(value: Cell): string {
if (typeof value === "number") return String(value); // numbers computed by the server
let text = value ?? "";
if (FORMULA_START.test(text)) {
text = `'${text}`; // apostrophe: the spreadsheet shows text, does not compute a formula
}
return `"${text.replaceAll('"', '""')}"`;
}FORMULA_START checks the first character: =, +, -, @, a tab and new-line characters, plus their full-width counterparts, which OWASP also lists. Such a text gets an apostrophe at the start, then every text lands in quotes, and a quote inside is doubled. Those are three steps from the OWASP list, after which a spreadsheet should read the cell as text. Numbers computed by the server, like the count of reactions, stay numbers without quotes, so a minus sign on a negative number scares nobody. The message in the data does not change: the apostrophe exists only in the file.
One of the tests checks the example from the same OWASP page: the text =1+2";=1+2 tries to close the quote and open, after the semicolon, a new cell with a formula. After the quote is doubled it stays one cell, "'=1+2"";=1+2". OWASP honestly adds that no method works in all spreadsheets, and in Excel the protection may vanish after the file is saved and opened again. So treat the exported file as a report to read, not as data to send back.
toCsv itself joins cells with commas and rows with the characters \r\n, because that is how RFC 4180 separates records. An empty list gives just the header, so an empty channel does not knock the export over.
A file from the server: the Route Handler
A Route Handler is a route.ts file in the app folder that, instead of a page, returns any response, here a file. The Next.js documentation says it cannot live in the same segment as page.tsx, which is why the export has its own folder. Open app/c/[channel]/export/route.ts. The beginning looks like the channel page from lesson 7_1:
export async function GET(
_request: Request,
ctx: RouteContext<"/c/[channel]/export">,
) {
const { channel: name } = await ctx.params;
const me = await getCurrentMember();
const channel = findChannel(name);
if (!channel || !canSeeChannel(channel, me)) {
return new Response("No such channel", { status: 404 });
}GET in the function name means it handles an ordinary download of the address. RouteContext is a helper type from the documentation that knows the route parameters, and params is a promise, as in pages. A guest who types the export address of a private channel gets 404, and the file is never created. According to the documentation Route Handlers are not cached by default, so every export takes fresh messages. The end of the function builds the response:
return new Response("\uFEFF" + csv, {
headers: {
"Content-Type": "text/csv; charset=utf-8",
"Content-Disposition": `attachment; filename="${channel.name}-${dayKey(new Date())}.csv"`,
},
});Content-Type says it is CSV in UTF-8 encoding. Content-Disposition: attachment tells the browser to download the file instead of showing it and suggests a name, for example general-2026-11-14.csv. The \uFEFF character at the start is the BOM, an invisible encoding marker. Microsoft writes on the Excel help page (https://support.microsoft.com/en-us/office/opening-csv-utf-8-files-correctly-in-excel-8a935af5-3416-4edd-ba7e-3dfd2bc4a032) that a UTF-8 CSV file with a BOM opens normally, and without it you need an import through the Data tab. The rows get the date in the Warsaw zone from the stamp function, a neighbour of dayKey from the previous lesson, the author, the text and the number of reactions.
The link in components/ChannelHeader.tsx is a plain <a> tag with the address /c/<channel>/export, not Link from Next.js. The documentation notes that Route Handlers do not take part in client-side navigation, which Link handles.
Without a server: a file from the browser
When the data is already in the browser, for example in the editor below, where there is no server, the page builds the file itself:
function downloadCsv(csv, filename) {
const blob = new Blob(["\uFEFF" + csv], { type: "text/csv;charset=utf-8" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename;
link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}A Blob is a file kept in the browser's memory, URL.createObjectURL gives it a temporary address, and a link with the download attribute downloads it under the given name. After a moment URL.revokeObjectURL frees the address, because according to MDN you call it when the address is no longer needed. In Ship's Comms the Route Handler wins, though: the server checks access before it sends anything, and only the data that the logged-in member may see anyway reaches the browser.
PDF: print instead of a library
The report for the ship owner is the dashboard from the previous lesson, so the PDF comes from the same page.
Request for Claude Code:
Add a "Print or save PDF" button to the dashboard that opens the
print window. The printout should keep only the report, without the
sidebar and the buttons. No PDF library. Check the printout of a
longer page, that nothing is cut off.Claude added a small client component components/PrintButton.tsx to the dashboard:
"use client";
export function PrintButton() {
return (
<button
type="button"
onClick={() => window.print()}
className="rounded-md border border-gray-300 bg-white px-3 py-1.5 text-sm font-semibold hover:bg-gray-50 print:hidden"
>
Print or save PDF
</button>
);
}window.print() opens the browser's print window, and there you choose saving to PDF. The component needs "use client", because it reacts to a click. print: is a Tailwind variant for @media print, that is, styles that work only when printing: print:hidden hides the button, and the same class on the sidebar in components/Sidebar.tsx leaves only the report on paper. A PDF library would be one more dependency and a separate page layout to maintain, while print uses the same HTML and the same fonts as the dashboard. In the PDF saved from Chrome the headings and member names came out unchanged, for example the heading "Most active members".
We checked one print trap on a longer channel page. The message list scrolls inside a box with overflow-y-auto, and Chrome printed only what fit in the box: ten of eleven messages, and of the last one only the author's name. The class print:overflow-visible lifts that limit for printing, and the same printout took two pages. The dashboard has the same layout, so it got that class right away, before it grows past one page.
Captain's review
- The guest and the export. In
lib/session.tschange the logged-in member tomerchantand open/c/captains-secrets/exportand/c/treasure-hunts/export. For us both addresses answered 404, and/c/trade/exportdownloaded a file. A typical agent mistake: an access check on the channel page but not in the Route Handler standing right next to it. - Every cell. Look in the diff for
join(",")withoutescapeCell. An agent often escapes quotes and forgets formulas, or the other way round, so the test with=and the test with a comma must stand side by side. - The file in hand. Write on
#generala message with a comma, a quote and a second line (Shift+Enter) and another one starting with=, download the CSV and open it in a spreadsheet. For us the file started with the BOM bytesEF BB BF, and a CSV parser read each of the two messages as one record with four cells. - Proof. Tests, lint, types and build. Before the first build
npx tsc --noEmitreports an error atRouteContext<"/c/[channel]/export">, because route types are generated only bynext buildornext dev; it is the same trap asPagePropsin lesson 7_1. Before the commit also run/code-review: an export is the place where data leaves the app, so a second look pays off.
Next step
Ask for a commit, for example "CSV export and dashboard print". Then a small step with the same function:
Add under the channel table on the dashboard an "Export CSV" link to
the /panel/export Route Handler, which uses toCsv and the same
channels as the dashboard. First a test that a guest does not get
the row of a private channel. At the end tests, lint, types and build.In the editor below waits the export in miniature: add a message with a comma, a quote or = at the start and compare how many records the parser reads from the file glued by join(",") and how many from toCsv. The "Export CSV" button downloads the file through a Blob.
Remember: whoever releases a report without a test releases cargo without customs control, and the quote and the apostrophe are the seals that make sure nobody sneaks gunpowder in at the port.
Code for this lesson: App.jsx
// The export in miniature: escapeCell and toCsv from the lesson next to joining with join(","),
// reading the file with a CSV parser and downloading through a Blob. In the project the file is built by the Route Handler
// /c/[channel]/export, which checks canSeeChannel first.
import { useState } from 'react';
const FORMULA_START = /^[=+\-@\t\r\n=+-@]/;
function escapeCell(value) {
if (typeof value === 'number') return String(value);
let text = value ?? '';
if (FORMULA_START.test(text)) text = "'" + text;
return '"' + text.replaceAll('"', '""') + '"';
}
function toCsv(header, rows) {
return [header, ...rows].map((row) => row.map(escapeCell).join(',')).join('\r\n');
}
// The agent's first version: no escaping
function naiveCsv(header, rows) {
return [header, ...rows].map((row) => row.join(',')).join('\n');
}
// A simple RFC 4180 parser: this is how a program that knows the standard reads the file
function parseCsv(text) {
const records = [];
let row = [];
let cell = '';
let quoted = false;
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (quoted) {
if (ch === '"' && text[i + 1] === '"') {
cell += '"';
i++;
} else if (ch === '"') quoted = false;
else cell += ch;
} else if (ch === '"' && cell === '') quoted = true;
else if (ch === ',') {
row.push(cell);
cell = '';
} else if (ch === '\n') {
row.push(cell);
records.push(row);
row = [];
cell = '';
} else if (ch !== '\r') cell += ch;
}
row.push(cell);
records.push(row);
return records;
}
function downloadCsv(csv, filename) {
const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
const header = ['Date', 'Author', 'Text', 'Reactions'];
const start = [
['2026-11-14 09:00', 'Anne Bonny', 'For tomorrow: water, rum and "hardtack"\nthe rest in the hold', 2],
['2026-11-14 09:05', 'Jack Rackham', '=HYPERLINK("https://example.com";"Treasure map")', 0],
];
function Records({ title, csv, rows }) {
const records = parseCsv(csv);
return (
<section className="rounded-lg border border-gray-200 bg-white p-3">
<h2 className="font-semibold">{title}</h2>
<pre className="mt-2 overflow-x-auto rounded-md bg-gray-100 p-2 text-xs">{csv}</pre>
<p className="mt-2 text-sm">
Records read by the parser: <strong>{records.length}</strong> (the header and {rows} messages)
</p>
<ol className="mt-1 list-decimal pl-5 text-xs text-gray-700">
{records.map((r, i) => (
<li key={i}>{r.length} cells: {r.map((c) => '[' + c.replaceAll('\n', ' / ') + ']').join(' ')}</li>
))}
</ol>
</section>
);
}
export default function App() {
const [rows, setRows] = useState(start);
const [text, setText] = useState('');
function add(e) {
e.preventDefault();
if (!text.trim()) return;
setRows([...rows, ['2026-11-14 10:00', 'Captain Redbeard', text, 0]]);
setText('');
}
return (
<div className="min-h-screen bg-gray-50 p-4 text-gray-900">
<form onSubmit={add} className="mb-4 rounded-lg border border-gray-200 bg-white p-3">
<label htmlFor="text" className="text-sm font-semibold">Add a message (a comma, a quote, = at the start)</label>
<textarea id="text" rows={2} value={text} onChange={(e) => setText(e.target.value)} className="mt-1 w-full rounded-md border border-gray-300 p-2 text-sm" />
<div className="mt-2 flex flex-wrap gap-2">
<button className="rounded-md bg-blue-700 px-3 py-1 text-sm font-semibold text-white">Add</button>
<button type="button" onClick={() => downloadCsv(toCsv(header, rows), 'general.csv')} className="rounded-md bg-green-700 px-3 py-1 text-sm font-semibold text-white">
Export CSV
</button>
</div>
</form>
<div className="grid gap-3 md:grid-cols-2">
<Records title='join(",") without escaping' csv={naiveCsv(header, rows)} rows={rows.length} />
<Records title="toCsv with escapeCell" csv={toCsv(header, rows)} rows={rows.length} />
</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. Which response headers of the Route Handler /c/[channel]/export make the browser download the CSV file instead of showing it?
2. How does escapeCell write the text For tomorrow: water, rum and "hardtack" so that it stays in one cell?
These are 2 of 8 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Export data to a CSV file
- Vertical ordering
Order the steps for downloading a CSV file built in the browser, without a server:
- Horizontal ordering
Arrange on one line the matcher of the PostToolUse hook from .claude/settings.json that fires after Edit and Write:
Tasks after this lesson
- QuestionQuiz: File download headers
- QuestionQuiz: A comma and a quote in a cell
- Coding taskPractice: Export a CSV report
- Put in orderSorting: Downloading the CSV file
- QuestionQuiz: PDF from the print view
- QuestionQuiz: A chart for a screen reader
- QuestionQuiz: Formula injection in CSV
- Put in orderSorting: Hook matcher
- QuestionQuiz: A hook or a line in CLAUDE.md
- QuestionQuiz: When Notification runs
- QuestionQuiz: Why jq and file_path in a hook
- Project to submitSend Ship's Comms to mentor
- VideoModule summary