Vibe coding with Claude Code course Β· Module 15: Advanced Claude Code
Code security from Claude Code: the checklist before you publish
In this lesson12
Treasure Map is about to sail into open water: one more feature and the first deployment, as in lesson 10_5. The feature is editing a pin. The owner changes the title and the tags, and the "Suggest tags" button asks an outside service for proposals. Claude delivered it in a quarter of an hour: tests green, the build passes, everything looks right in the browser. The form will not send an empty title, and you cannot type a hundred-and-first character. What the screen does not show are two things. The server accepts whatever reaches it, because required and maxLength work only in the browser. And the key to the tags service sits in the client code, so every visitor downloads it together with the page. This lesson gives you a code security checklist: Claude walks through it, and you check its report.
What you already know
Lesson 14_7 guarded what the agent can do on your computer: auto mode, deny rules and the sandbox. This lesson guards what its code will do to your users. You know most of the points: the key in the hold from lesson 8_4, the NEXT_PUBLIC_ prefix and the key in the build from lesson 10_5, a lock in every route from lessons 11_3 and 13_2, the allow-list of fields from lesson 13_5, /security-review from lesson 8_7 and the /pre-publish skill from lesson 10_7. Here you fold them into one list for the application code and add the security headers and npm audit.
Request for Claude Code
A list makes sense only when every point ends with proof, so you ask for a file and a line, not for an assurance. Claude changes nothing, and gets the files through @:
Before publishing, walk through the code security list for Treasure Map.
Change nothing. Files: @components/EditPinForm.tsx,
@app/api/pins/[id]/route.ts, @app/api/pins/route.ts,
@app/api/boards/[id]/route.ts, @next.config.ts.
Points: (1) a key in a NEXT_PUBLIC_ variable or process.env in a component
with "use client"; (2) every write route checks the session and the owner
before it changes anything; (3) data from the request body goes through a Zod
schema with an allow-list of fields on the server; (4) every handler returns
a Response in every branch; (5) security headers in next.config.ts. Result:
a table with the columns point, file and line, PASSED or FAILED, proof.What Claude answered
We ran this request in -p mode, with Sonnet and read-only tools. The answer came as a table. Three of its rows, shortened, looked like this:
(1) Secrets | components/EditPinForm.tsx:12 | FAILED | The component has "use client" and reads process.env.NEXT_PUBLIC_TAGS_API_KEY, so the key ends up in the browser bundle.
(2) Session and owner, pin PATCH | app/api/pins/[id]/route.ts:14-16 | FAILED | It only checks that there is a session. Any signed-in user can change someone else's pin.
(3) Zod on the server, pin PATCH | app/api/pins/[id]/route.ts:15-16 | FAILED | Values from request.json() go to updatePin without a schema.The table is a scout's report, not a verdict. Every FAILED row you check yourself, like the report in lesson 8_7: you open the file in Cursor at the given line and try to reproduce the problem. Read the table, not the summary: the sentence above it spoke of three failed points out of five, while in the table every point had at least one FAILED row. Below the table Claude added a remark we had not asked for: since the key was in the bundle, treat it as exposed and replace it.
Point 1: the key stays on the server
The line Claude pointed at looks innocent:
// components/EditPinForm.tsx (agent's version)
headers: { Authorization: `Bearer ${process.env.NEXT_PUBLIC_TAGS_API_KEY}` },The NEXT_PUBLIC_ prefix tells Next.js to write the variable's value into the code sent to the browser, already at build time. In our case, after next build the key with the prefix ended up in a file in .next/static/chunks, while the key without the prefix, read only on the server, did not appear there even once. Lint, tsc and the build stayed silent. The fix is the pattern from lesson 8_4: the route app/api/tags/route.ts reads process.env.TAGS_API_KEY and asks the service itself, and the form calls only our route. A key that has reached a deployed bundle even once you replace at the provider, because you do not know who downloaded it.
Point 2: locks in every write route
The agent's version checked only whether someone was signed in, so in our test the Captain changed the title of Polly's pin with one curl command. The corrected route starts with the locks, in this order:
// app/api/pins/[id]/route.ts
const viewerId = await getCurrentUserId();
if (!viewerId) return Response.json({ error: "Sign in." }, { status: 401 });
const ownerId = await getPinOwner(id);
if (!ownerId) return Response.json({ error: "No such pin." }, { status: 404 });
if (ownerId !== viewerId) return Response.json({ error: "Only the author edits a pin." }, { status: 403 });getPinOwner and updatePin are two small functions from lib/pinStore.ts: the first reads just the ownerId field from the database, the second saves the title and the tags. The owner comes from the database and the signed-in user from the session, never from the request body. The order matters: a stranger gets a refusal before the server reads a single field of the form.
Point 3: validation on the server
The attributes required and maxLength are a courtesy for an honest visitor, not a guard, because curl never opens the form. In our test the agent's version without a schema accepted with code 200 a title of three spaces, seven tags and a title of five thousand characters, and the database saved all of it. So the server holds the allow-list of fields from lesson 13_5, this time for editing:
// lib/pinInput.ts
export const pinEditSchema = z.strictObject({
title: z.string().trim().min(1, "Enter a title.").max(100, "The title has at most 100 characters."),
tags: z.array(z.string().trim().min(1).max(30)).max(5, "At most 5 tags."),
});The schema lets through only the title and the tags. Editing cannot change the image, the dimensions or the owner, and z.strictObject rejects every field outside the list, ownerId included. The attributes in the form stay, because they save honest users a needless round trip to the server, but the border runs through the route.
Point 4: a response in every branch
Beware of a fix that only looks finished. This handler stood as the model in the old version of this lesson:
// app/api/pins/[id]/route.ts (buggy version)
const body = await request.json();
try {
const data = pinEditSchema.parse(body);
await updatePin(id, data);
} catch {
return Response.json({ error: "Invalid data." }, { status: 400 });
}Bad data gets 400, but after a successful save the function ends without return, that is, it returns undefined. Next.js then answers with code 500, and in the next start log it writes No response is returned from route handler with advice to return a Response in all branches. Worst of all, the change has already reached the database: the client sees an error and clicks again. tsc, lint and the build let this handler through, and only a test with expect(res).toBeInstanceOf(Response) caught it. On top of that, catch catches every exception, so a database outage would also be presented as bad data. The corrected second half of the route answers in every branch:
const body = await request.json().catch(() => null);
const result = pinEditSchema.safeParse(body);
if (!result.success) {
return Response.json({ error: "Fix the fields.", fields: z.flattenError(result.error).fieldErrors }, { status: 400 });
}
const pin = await updatePin(id, result.data);
return Response.json(pin);safeParse does not throw, it returns a result with a success field, so every path ends with an explicit return, and a body that is not JSON gives 400 instead of 500. In our test curl got, in turn, 401 without the cookie, 403 as a stranger, 400 for an empty title and for the ownerId field, 404 for a nonexistent pin and 200 for the owner. By the way: the old lesson validated an address with z.string().email(), which current Zod marks as deprecated. Today you write z.email().
Point 5: security headers
Headers are instructions for the browser, attached to every response. The old version of the lesson set them in next.config.js through module.exports, and the examples in the Next.js documentation look the same, so an agent will gladly copy that form. A project from create-next-app has, however, a next.config.ts with export default, and you add the headers to it:
// next.config.ts
const securityHeaders = [
{ key: "X-Content-Type-Options", value: "nosniff" },
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
{ key: "X-Frame-Options", value: "DENY" },
{ key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" },
];The first forbids the browser to guess a file's type, the second limits the address revealed to other sites, the third does not let Treasure Map be embedded in a frame (iframe) on any site, and the fourth turns off the camera, the microphone and the location, which the app does not use, because the magnifier takes its picture from a file. In the nextConfig object, next to turbopack, two entries are added:
poweredByHeader: false,
async headers() {
return [{ source: "/:path*", headers: securityHeaders }];
},source: "/:path*" covers every path, API routes too, and poweredByHeader: false removes the X-Powered-By header, which gives away the framework. You check on the built application: npm run build, npm run start and in a second terminal curl -sI localhost:3000/api/pins/p01. In our case under HTTP/1.1 200 OK stood all four headers and not a trace of X-Powered-By.
The strongest header, Content-Security-Policy, lists the allowed sources of scripts, styles and images. The Next.js documentation has a separate guide for it: without one-time codes (nonces) you set it in the same headers(), and with them every page must render dynamically. A policy requires listing every source the application uses, so it is a separate step, checked in the browser, not a line copied from a tutorial.
Point 6: npm audit with judgement
npm audit sends the npm registry a description of the project's dependencies and prints the known vulnerabilities in their versions. When it finds even one, it exits with a nonzero code. In our Treasure Map (as of November 2026) it reported eight vulnerabilities of moderate severity, and the first looked like this:
minimatch 7.0.0 - 11.0.0
Severity: moderate
fix available via `npm audit fix --force`
Will install eslint-config-next@15.5.29, which is a breaking changeYou read the report starting from the question of where that package works. All eight entries are one chain: minimatch in the typescript-eslint tools used by eslint-config-next, that is, lint on your computer, not code at your users. The proposed fix would roll the lint configuration back to an older Next.js line, because according to the npm documentation --force installs versions outside the range in package.json, breaking changes included. The application code is checked by npm audit --omit=dev, which skips development dependencies. In our case it answered found 0 vulnerabilities. A vulnerability in a production dependency you fix at once and verify with tests, and a vulnerability in a tool you write down and wait for the release that removes it.
Point 7: /security-review on the branch
The list catches what you know to look for. /security-review from lesson 8_7 looks for what you did not think of: it compares the branch with the default branch of origin and reads the changes for injections, authentication errors and data leaks. We did not run it on this branch, so we do not show a report. Every finding has a severity (Severity) and a confidence (Confidence), but both are the model's assessment, not proof. You open the indicated file, try to reproduce the attack with a curl command or a test, and only then decide. An accepted point you fix with a narrow request and a test that fails without the fix, and for a rejected one you write down what you rejected it with. An empty report does not mean the list is superfluous, because a review can miss a real but not very dangerous finding.
Captain's review
- Secrets.
grep -rn NEXT_PUBLIC_ app componentsshows no key, and after the build a fragment of any key gives zero hits in.next/static. - Locks. Every write route has a test for no session and for someone else's user.
- Every branch. The success test checks that the handler returned a
Responsewith the right code, not only that the data was saved. - Headers and packages.
curl -sIshows four headers, and everynpm auditentry has your decision.
A typical agent mistake: validation only in the browser. Claude adds required, maxLength or a check in onSubmit and reports that the data is checked, while the route still accepts the body without a schema. You will recognise it in the diff: the changes are in the component and there is no safeParse in the route. You will confirm it with a curl command, which does not see the form at all.
Next step
You order the fixes one per point, with a test and a commit after each. Then you make the list permanent, so that it does not depend on your memory: "Add to the /pre-publish skill from lesson 10_7 a Code security part: points 1-5 from our list and npm audit --omit=dev, and for the captain /security-review and curl -sI on the built application. The skill fixes nothing". If Treasure Map does not have this skill yet, Claude will create it. You read the change in SKILL.md in the diff like code, and then a commit, for example "Code security before publishing". In the editor below a checklist is waiting: switch on the agent's mistakes in the route and in the configuration and see which point catches them.
Remember: the attributes of a form are a courtesy for an honest crew, and the locks on the server are the only guard that a pirate cannot go around.
Code for this lesson: App.tsx
// Checklist before publishing: switch on the mistakes of the agent and see which point catches them
import { useState } from 'react';
export type Status = 'PASSED' | 'FAILED';
export type ConfigFile = 'ts' | 'js';
export type Scenario = 'no session' | 'stranger' | 'empty title' | 'ownerId field' | 'owner';
export interface Setup {
keyInClient: boolean;
sessionCheck: boolean;
ownerCheck: boolean;
serverSchema: boolean;
catchJson: boolean;
returnsOnSuccess: boolean;
headers: boolean;
configFile: ConfigFile;
prodVulns: number;
devVulns: number;
}
export interface Row {
point: string;
status: Status;
proof: string;
}
export interface Outcome {
status: number;
saved: boolean;
}
export const SCENARIOS: Scenario[] = ['no session', 'stranger', 'empty title', 'ownerId field', 'owner'];
export const SAFE: Setup = {
keyInClient: false,
sessionCheck: true,
ownerCheck: true,
serverSchema: true,
catchJson: true,
returnsOnSuccess: true,
headers: true,
configFile: 'ts',
prodVulns: 0,
devVulns: 8,
};
export const AGENT: Setup = { ...SAFE, keyInClient: true, ownerCheck: false, serverSchema: false, catchJson: false, headers: false };
export const OLD_LESSON: Setup = { ...SAFE, sessionCheck: false, ownerCheck: false, catchJson: false, returnsOnSuccess: false, configFile: 'js' };
const OWNER = 'polly';
function viewerOf(sc: Scenario): string | null {
if (sc === 'no session') return null;
if (sc === 'stranger') return 'captain';
return OWNER;
}
// What the PATCH /api/pins/p01 route will answer and whether the pin changes in the database
export function simulate(s: Setup, sc: Scenario): Outcome {
const viewer = viewerOf(sc);
if (s.sessionCheck && viewer === null) return { status: 401, saved: false };
if (s.ownerCheck && viewer !== OWNER) return { status: 403, saved: false };
const invalid = sc === 'empty title' || sc === 'ownerId field';
if (s.serverSchema && invalid) return { status: 400, saved: false };
if (!s.returnsOnSuccess) return { status: 500, saved: true };
return { status: 200, saved: true };
}
export function checklist(s: Setup): Row[] {
const rows: Row[] = [];
rows.push(
s.keyInClient
? { point: '1. Secrets', status: 'FAILED', proof: 'EditPinForm.tsx has "use client" and reads process.env.NEXT_PUBLIC_TAGS_API_KEY: the key will land in .next/static. Move the call to a route and replace the key at the provider.' }
: { point: '1. Secrets', status: 'PASSED', proof: 'Only the server route reads the key: process.env.TAGS_API_KEY, without the NEXT_PUBLIC_ prefix.' },
);
const stranger = simulate(s, 'stranger');
const anonymous = simulate(s, 'no session');
if (anonymous.saved) {
rows.push({ point: '2. Locks', status: 'FAILED', proof: 'curl without a cookie changes the pin: the route does not check the session.' });
} else if (stranger.saved) {
rows.push({ point: '2. Locks', status: 'FAILED', proof: 'The Captain changes the pin of Polly: no comparison of ownerId with viewerId and no 403 response.' });
} else {
rows.push({ point: '2. Locks', status: 'PASSED', proof: '401 without a session and 403 for a stranger, before the server reads the body.' });
}
rows.push(
s.serverSchema
? { point: '3. Validation', status: 'PASSED', proof: 'pinEditSchema.safeParse on the server: only title and tags, z.strictObject rejects ownerId.' }
: { point: '3. Validation', status: 'FAILED', proof: 'Only required and maxLength in the form: curl saves a title of three spaces and seven tags.' },
);
if (!s.returnsOnSuccess) {
rows.push({ point: '4. Response', status: 'FAILED', proof: 'No return after the save: 500 and No response is returned from route handler, and the change is already in the database.' });
} else if (!s.catchJson) {
rows.push({ point: '4. Response', status: 'FAILED', proof: 'request.json() without .catch: a body that is not JSON ends in 500 instead of 400.' });
} else {
rows.push({ point: '4. Response', status: 'PASSED', proof: 'Every branch ends with a return of a Response: 400, 401, 403, 404 or 200.' });
}
if (s.configFile === 'js') {
rows.push({ point: '5. Headers', status: 'FAILED', proof: 'Copied from a tutorial: next.config.js and module.exports. The project has next.config.ts with export default, add headers() there.' });
} else if (!s.headers) {
rows.push({ point: '5. Headers', status: 'FAILED', proof: 'curl -sI does not show X-Content-Type-Options, Referrer-Policy, X-Frame-Options or Permissions-Policy.' });
} else {
rows.push({ point: '5. Headers', status: 'PASSED', proof: 'curl -sI on the built application shows four headers and does not show X-Powered-By.' });
}
if (s.prodVulns > 0) {
rows.push({ point: '6. npm audit', status: 'FAILED', proof: 'npm audit --omit=dev: ' + s.prodVulns + ' in production dependencies. Fix them, run the tests, no blind --force.' });
} else if (s.devVulns > 0) {
rows.push({ point: '6. npm audit', status: 'PASSED', proof: 'npm audit --omit=dev: found 0 vulnerabilities. ' + s.devVulns + ' in development tools: write down the decision and wait for the release.' });
} else {
rows.push({ point: '6. npm audit', status: 'PASSED', proof: 'npm audit: found 0 vulnerabilities.' });
}
return rows;
}
export function routeCode(s: Setup): string[] {
const lines = ['export async function PATCH(request: Request, { params }: Ctx) {', ' const { id } = await params;'];
if (s.sessionCheck) {
lines.push(' const viewerId = await getCurrentUserId();');
lines.push(' if (!viewerId) return Response.json({ error: "Sign in." }, { status: 401 });');
}
if (s.ownerCheck) {
lines.push(' const ownerId = await getPinOwner(id);');
lines.push(' if (!ownerId) return Response.json({ error: "No such pin." }, { status: 404 });');
lines.push(' if (ownerId !== viewerId) return Response.json({ error: "Only the author edits a pin." }, { status: 403 });');
}
lines.push(s.catchJson ? ' const body = await request.json().catch(() => null);' : ' const body = await request.json();');
if (s.serverSchema) {
lines.push(' const result = pinEditSchema.safeParse(body);');
lines.push(' if (!result.success) return Response.json({ error: "Fix the fields." }, { status: 400 });');
lines.push(' const pin = await updatePin(id, result.data);');
} else {
lines.push(' const pin = await updatePin(id, { title: body.title, tags: body.tags });');
}
lines.push(s.returnsOnSuccess ? ' return Response.json(pin);' : ' // no return after the save');
lines.push('}');
return lines;
}
const STATUS_CLASS: Record<Status, string> = {
PASSED: 'text-emerald-400',
'FAILED': 'text-rose-400',
};
function Toggle(props: { label: string; checked: boolean; onChange: (v: boolean) => void }) {
return (
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={props.checked} onChange={(e) => props.onChange(e.target.checked)} />
{props.label}
</label>
);
}
export default function App() {
const [s, setS] = useState<Setup>(AGENT);
const set = <K extends keyof Setup>(key: K, value: Setup[K]) => setS({ ...s, [key]: value });
const rows = checklist(s);
const failed = rows.filter((r) => r.status === 'FAILED').length;
return (
<div className="min-h-screen space-y-4 bg-slate-950 p-4 text-slate-100">
<h1 className="text-xl font-bold">Checklist before publishing</h1>
<p className="text-sm text-slate-300">Editing a pin in Treasure Map. Switch what the agent wrote and see which point of the list catches it.</p>
<div className="flex flex-wrap gap-2 text-sm">
<button type="button" className="rounded bg-slate-800 px-2 py-1 hover:bg-slate-700" onClick={() => setS(AGENT)}>Agent version</button>
<button type="button" className="rounded bg-slate-800 px-2 py-1 hover:bg-slate-700" onClick={() => setS(OLD_LESSON)}>Pattern from the old lesson</button>
<button type="button" className="rounded bg-slate-800 px-2 py-1 hover:bg-slate-700" onClick={() => setS(SAFE)}>After the fixes</button>
</div>
<div className="grid gap-2 md:grid-cols-2">
<Toggle label="key in NEXT_PUBLIC_ in a client component" checked={s.keyInClient} onChange={(v) => set('keyInClient', v)} />
<Toggle label="route checks the session (401)" checked={s.sessionCheck} onChange={(v) => set('sessionCheck', v)} />
<Toggle label="route checks the owner (403)" checked={s.ownerCheck} onChange={(v) => set('ownerCheck', v)} />
<Toggle label="Zod schema on the server" checked={s.serverSchema} onChange={(v) => set('serverSchema', v)} />
<Toggle label="request.json() with .catch" checked={s.catchJson} onChange={(v) => set('catchJson', v)} />
<Toggle label="return after a successful save" checked={s.returnsOnSuccess} onChange={(v) => set('returnsOnSuccess', v)} />
<Toggle label="headers() in the configuration" checked={s.headers} onChange={(v) => set('headers', v)} />
<Toggle label="configuration as next.config.js with module.exports" checked={s.configFile === 'js'} onChange={(v) => set('configFile', v ? 'js' : 'ts')} />
<label className="flex items-center gap-2 text-sm">
vulnerabilities in production dependencies
<input className="w-16 rounded bg-slate-900 p-1 font-mono" value={s.prodVulns} onChange={(e) => set('prodVulns', Math.max(0, Number(e.target.value) || 0))} />
</label>
</div>
<div className="overflow-x-auto rounded bg-slate-900 p-2 font-mono text-xs">
{routeCode(s).map((line, i) => (
<div key={i} className="whitespace-pre">{line}</div>
))}
</div>
<table className="w-full text-left text-sm">
<thead>
<tr className="text-slate-400">
<th className="p-1">curl</th>
<th className="p-1">code</th>
<th className="p-1">pin in the database</th>
</tr>
</thead>
<tbody>
{SCENARIOS.map((sc) => {
const o = simulate(s, sc);
return (
<tr key={sc} className="border-t border-slate-800">
<td className="p-1">{sc}</td>
<td className="p-1 font-mono">{o.status}</td>
<td className={'p-1 ' + (o.saved && (sc !== 'owner' || o.status !== 200) ? 'text-rose-400' : 'text-slate-300')}>{o.saved ? 'changed' : 'unchanged'}</td>
</tr>
);
})}
</tbody>
</table>
<ul className="space-y-2 text-sm">
{rows.map((r) => (
<li key={r.point} className="rounded border border-slate-800 p-2">
<span className="font-semibold">{r.point}: </span>
<span className={STATUS_CLASS[r.status]}>{r.status}</span>
<p className="text-slate-300">{r.proof}</p>
</li>
))}
</ul>
<p className="text-sm">{failed === 0 ? 'The list is clean. What remains is /security-review on the branch and your decision on every finding.' : 'To fix: ' + failed + '. One narrow request with a test for each point.'}</p>
</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. Claude put the tags service key in the NEXT_PUBLIC_TAGS_API_KEY variable and reads it in a component with "use client". Lint, tsc and the build pass. What do you do?
2. A PATCH handler saves the pin in a try block and has a return only in the catch for bad data. What does a client that sends valid data get?
These are 2 of 4 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Arrange the lines of the PATCH /api/pins/[id] handler so that a stranger gets a refusal before the server reads the data from the request body: