Vibe Coding: build real apps with AI · Episode 30. Every agent run below is real: Claude Code 2.1.322 (model claude-opus-5-5) in print mode (claude -p --permission-mode acceptEdits), on 12 November 2026, in /home/asha/projects/class-gallery. The agent could write files but needed approval to run commands, and nobody approved, so it ran nothing. We ran check.sh, ESLint, Prettier and Ravi's bot ourselves.
What was written by hand: the messy server.js (commit e6213a4, 103 lines) was written by hand for this video to look like a month of quick fixes. It is not the AI's code. The "full photo" edit and the photo typo were also made by hand, on screen, to show the problems. Asha, Ravi and Kabir are fictional.
Tools: Node.js v22, Express 5.3.0, better-sqlite3 13.1.1, ESLint 10.14.0 (with @eslint/js recommended rules), Prettier 3.10.1, jq, curl. No outside product facts are used in this episode beyond these installed versions.
The problem: the same masala in four jars
| A kitchen | Your code |
|---|---|
| Garam masala in 4 jars, in 4 corners: refill 3, forget 1 | Duplicated code: the same lines in 4 routes |
| Reorganise the kitchen; dinner must taste the same | Refactoring: new structure, same behaviour |
| Taste every dish before and after | A behaviour check: same requests, same answers |
The messy file (written by hand)
app.get("/api/search", (req, res) => {
let q = req.query.q || ""
if (q.length > 50) q = q.slice(0, 50)
let d = db.prepare(`SELECT p.*, (SELECT COUNT(*) FROM reactions r WHERE
r.photo_id = p.id AND r.kind = 'like') AS likes FROM photos p WHERE ...`).all(...)
let out = []
for (let i = 0; i < d.length; i++) {
let x = d[i]
x.v = fh("public/photos/small/" + x.file)
x.url = "/photos/small/" + x.file + "?v=" + x.v
out.push(x)
}
res.json(out)
})
// ...and the same loop again in /api/photos, /api/day/:day and /api/top
var h = new Map() // h? fh? d? x?
app.use("/photos", express.static("public/photos", { maxAge: 604800000 }))
Three smells: the same SQL and loop copied into four routes; names that say nothing (h, fh, d, x); and a magic number (604800000) with no name.
Copy-paste: a real bug
Asha adds a link to the full-size photo, x.full = "/photos/" + x.file, in the copies she finds: photos, search and day. She forgets the fourth copy, in /api/top.
$ curl -s localhost:3000/api/photos | jq '.[0].full'
"/photos/IMG_01.jpg"
$ curl -s localhost:3000/api/search?q=bus | jq '.[0].full'
"/photos/IMG_01.jpg"
$ curl -s localhost:3000/api/day/2026-11-03 | jq '.[0].full'
"/photos/IMG_13.jpg"
$ curl -s localhost:3000/api/top | jq '.[0].full'
null
Why: when the same logic lives in four places, every change has to be made four times: one change, four chances to forget.
What refactoring means
- Refactor: change how code is arranged inside, keep what it does.
- Behaviour: everything the outside world sees: answers, error messages, status codes, odd cases like an empty search.
- Adding a feature or fixing a bug is not a refactor (the behaviour changes). Keep them separate.
- If behaviour must not change, you need a way to prove it didn't.
A safety net first: check.sh
Asha wrote this before any refactor. It starts the server on a copy of the database, sends the same 19 requests every time, and saves every answer to a file:
#!/bin/sh
# Behaviour check: starts the server on a copy of the database, sends the same requests every time,
# and saves every answer to the file given (default: check-output.txt). Compare two runs with diff.
OUT=${1:-check-output.txt}
cp trip.db /tmp/check.db
TRIP_DB=/tmp/check.db node server.js > /dev/null 2>&1 &
PID=$!
sleep 1.5
{
for path in /api/photos "/api/search?q=bus" "/api/search?q=BUS" "/api/search?q=" /api/day/2026-11-03 /api/day/2026-12-25 \
/api/top "/api/top?n=3" "/api/top?n=0" "/api/top?n=100" /api/photos/16/likes /api/photos/16/comments /api/photos/99/comments; do
echo "GET $path"; curl -s "localhost:3000$path"; echo
done
for body in '{"name":"Neha","body":"Nice!"}' '{"name":"","body":"x"}' '{"name":" Ravi ","body":" ok "}'; do
echo "POST comments $body"; curl -s -w " %{http_code}" -H 'Content-Type: application/json' -d "$body" localhost:3000/api/photos/16/comments; echo
done
for body in '{"viewer":"parent7"}' '{"viewer":""}'; do
echo "POST like $body"; curl -s -w " %{http_code}" -H 'Content-Type: application/json' -d "$body" localhost:3000/api/photos/16/like; echo
done
echo "GET /api/photos/16/comments"; curl -s localhost:3000/api/photos/16/comments; echo
} > "$OUT"
kill $PID
echo "saved $(grep -c '^GET\|^POST' "$OUT") answers to $OUT"
$ ./check.sh before.txt
saved 19 answers to before.txt
The odd cases (a search in capitals, n=0, n=100, a comment with no name) are where refactors break things. A sample of the saved answers:
POST comments {"name":"","body":"x"}
{"error":"Name and comment are required."} 400
POST like {"viewer":"parent7"}
{"likes":2489} 201
This is a characterization check: it records what the code does today, right or wrong, so you notice if anything changes.
The same idea, small (run in the compiler)
const photos = [{ file: "IMG_01.jpg", v: "5267" }, { file: "IMG_16.jpg", v: "0e66" }];
// before: the same lines, copied into four routes
function oldWay(list) {
let out = [];
for (let i = 0; i < list.length; i++) {
let x = { ...list[i] };
x.url = "/photos/small/" + x.file + "?v=" + x.v;
out.push(x);
}
return out;
}
// after: one well-named function, used everywhere
function withThumbnail(photo) {
return { ...photo, url: `/photos/small/${photo.file}?v=${photo.v}` };
}
const newWay = (list) => list.map(withThumbnail);
const before = JSON.stringify(oldWay(photos));
const after = JSON.stringify(newWay(photos));
console.log(after);
console.log(before === after ? "SAME behaviour" : "CHANGED!");
Output:
[{"file":"IMG_01.jpg","v":"5267","url":"/photos/small/IMG_01.jpg?v=5267"},{"file":"IMG_16.jpg","v":"0e66","url":"/photos/small/IMG_16.jpg?v=0e66"}]
SAME behaviour
Pulling repeated lines into one named function is called extracting a function. Now a tiny slip: ?v=${photo.file} instead of ?v=${photo.v}:
[{"file":"IMG_01.jpg","v":"5267","url":"/photos/small/IMG_01.jpg?v=IMG_01.jpg"},{"file":"IMG_16.jpg","v":"0e66","url":"/photos/small/IMG_16.jpg?v=IMG_16.jpg"}]
CHANGED!
The photos would still load, so nobody would notice that caching broke (episode 29's problem). The check catches it at once.
Prompt 1 (real): "clean it up and make it professional"
claude -p "server.js has become a mess after a month of quick fixes. Clean it up and make it professional." --permission-mode acceptEdits
Read check.sh, before.txt
"The baseline shows the quirks I have to keep. n=0 falls back to 5,
n is capped at 24, search ignores case, and tied like counts come
out in id order."
Write server.js +154 -87 lines (103 -> 170)
Reply: one photo query + withThumbnail(), names, constants ...
"Bugs I left alone because fixing them changes behaviour: ..."
The bugs it listed but left alone: a POST without a JSON body gives a 500 instead of a 400; you can comment on or like a photo that doesn't exist; the same viewer can like the same photo any number of times. Right instinct: bug fixes are separate changes.
Our check:
$ ./check.sh after1.txt && diff before.txt after1.txt && echo IDENTICAL
saved 19 answers to after1.txt
IDENTICAL
We also ran the same prompt on a copy where check.sh had been deleted. The AI found it in Git history: "The deleted check.sh from the previous commit is a behaviour snapshot tool, so I'll use it to capture a baseline before refactoring and diff against it afterward."
Naming and magic numbers
// before // after (the AI's names)
var h = new Map() const fileVersionCache = new Map();
function fh(p) { ... } function fileVersion(filePath) { ... }
let d = db.prepare(...).all() queries.allPhotos.all()
let x = d[i] function withThumbnail(photo) { ... }
{ maxAge: 604800000 } const PHOTO_CACHE_MAX_AGE_MS =
7 * 24 * 60 * 60 * 1000; // one week
if (q.length > 50) const MAX_SEARCH_LENGTH = 50;
A good name says what something is, so you don't need a comment. When you see a bare number, ask "what is it?" and give it that name. Part of the AI's cleaned-up file:
/** Adds the thumbnail version hash and URL to a photo row. */
function withThumbnail(photo) {
const v = fileVersion(path.join(THUMBNAIL_DIR, photo.file));
return { ...photo, v, url: `${THUMBNAIL_URL_PREFIX}${photo.file}?v=${v}` };
}
function sendPhotos(res, rows) {
res.json(rows.map(withThumbnail));
}
/** Parses the `n` query param for /api/top: defaults to 5 when missing or 0, capped at 24. */
function parseTopCount(raw) {
const n = parseInt(raw, 10) || DEFAULT_TOP_COUNT;
return Math.max(0, Math.min(n, MAX_TOP_COUNT));
}
app.get("/api/photos", (req, res) => {
sendPhotos(res, queries.allPhotos.all());
});
app.get("/api/top", (req, res) => {
sendPhotos(res, queries.topPhotos.all(parseTopCount(req.query.n)));
});
Prompt 2 (real): splitting a large file
claude -p "Now split server.js into smaller files, like a real project has, so it's easier to find things." --permission-mode acceptEdits
server.js just starts the app (6 lines)
src/config.js port, database path, folders, limits
src/db.js database, index, prepared queries
src/app.js Express setup, mounts the routes under /api
src/routes/photos.js /photos /search /day/:day /top
src/routes/likes.js src/routes/comments.js
src/utils/today.js src/utils/fileVersion.js
$ ./check.sh after2.txt && diff before.txt after2.txt && echo IDENTICAL
IDENTICAL
A module is a file that shares some of its code with others (here with require and module.exports). Is nine files right for 170 lines? today.js has 8 lines. Split when a file is hard to find your way around, not because big projects look like that.
Lint and format: ESLint and Prettier
A linter reads code without running it and warns about likely mistakes. A formatter rewrites the layout (spaces, quotes, semicolons, line breaks) the same way every time, and never changes what the code does.
The project's ESLint config:
const js = require("@eslint/js");
const globals = require("globals");
module.exports = [
js.configs.recommended,
{ files: ["**/*.js"], languageOptions: { sourceType: "commonjs", globals: globals.node } },
{ ignores: ["node_modules/", "public/"] },
];
Real runs:
# our own typo, made by hand in one of the four copies:
x.full = "/photos/" + photo.file // there is no "photo" here
$ npx eslint server.js
73:27 error 'photo' is not defined no-undef
✖ 1 problem (1 error, 0 warnings)
$ npx prettier --check server.js src public/app.js
[warn] src/db.js
[warn] public/app.js # two files the AI wrote
$ npx prettier --write server.js src public/app.js
What Prettier changed in the messy file (part of the real diff):
-const fs = require('fs')
-db.exec("CREATE INDEX IF NOT EXISTS reactions_photo_kind ON reactions (photo_id, kind)")
-var h = new Map()
+const fs = require("fs");
+db.exec(
+ "CREATE INDEX IF NOT EXISTS reactions_photo_kind ON reactions (photo_id, kind)",
+);
+var h = new Map();
Prompt 3 (real): dead code
claude -p "Last cleanup: remove dead code, anything the app doesn't use anymore." --permission-mode acceptEdits
Edit src/db.js module.exports = { queries }; (db was unused)
Reply: "What I left alone, because the page doesn't use it but
something outside it might:"
- the url field in photo responses
- /api/day, /api/top, comments, POST /like
- GET /api/photos/:id/likes: "kept on purpose for old clients"
Dead code is code nothing uses any more. But unused in this folder doesn't mean unused: Ravi's class bot, a separate project from episode 18, calls that endpoint every evening.
// Ravi's class bot (episode 18): every evening it posts the photo of the day with its likes.
const GALLERY = process.env.GALLERY || "http://localhost:3000";
const day = new Date().getDate() % 24 + 1; // a different photo each day
(async () => {
const res = await fetch(`${GALLERY}/api/photos/${day}/likes`);
if (!res.ok) throw new Error(`Gallery answered ${res.status} ${res.statusText}`);
const { likes } = await res.json();
console.log(`Photo of the day: #${day} · ❤ ${likes} → ${GALLERY}/#photo-${day}`);
})();
(Between prompts 3 and 4 we also asked the agent to move the page's script into public/app.js and split it into small named functions; the page still loaded 24 cards and made one search call, which we checked in a browser.)
The real AI slip: a "rename" that broke a bot
claude -p "likes is a confusing name, it's a count. Rename it to likeCount everywhere." --permission-mode acceptEdits
Edit src/db.js AS likes -> AS likeCount (3 places)
Edit public/app.js photo.likes -> photo.likeCount
Reply (last paragraph): "Decision for you: old clients will break.
The JSON field the API sends is now named likeCount ...
If anything still reads the old field, I can have that one
endpoint keep returning likes."
The "decision" had already been made: the change was in the files. Our check and the bot:
$ ./check.sh after5.txt && diff before.txt after5.txt
< {"likes":2488}
> {"likeCount":2488} ... 11 of 19 answers changed
# Ravi's class bot, a separate project (episode 18):
$ node ../class-bot/photo-of-the-day.js
Photo of the day: #13 · ❤ undefined → http://localhost:3000/#photo-13
Lesson: renaming something inside your code is a refactor. Renaming something other programs read (a JSON field, a web address) changes behaviour: a breaking change. Breaking changes should be a question before, not a note after.
Prompt 5 (real): the rule and the evidence
claude -p "Ravi's class bot is a separate project that calls GET /api/photos/:id/likes and reads likes. Tonight it posted: Photo of the day: #13 · ❤ undefined. Keep the new name inside our code if you like, but every JSON field the API sends must stay exactly as before. check.sh and before.txt are how I check." --permission-mode acceptEdits
Edit src/routes/photos.js likeCount inside -> "likes" in the JSON
Edit src/routes/likes.js likesResponse(): { likes: N }
Reply: "the change in src/db.js that hasn't been committed yet ...
your internal rename is kept as it was."
$ ./check.sh after6.txt && diff before.txt after6.txt && echo IDENTICAL
IDENTICAL
$ node ../class-bot/photo-of-the-day.js
Photo of the day: #13 · ❤ 2568 → http://localhost:3000/#photo-13
The fix:
/** Like count in the API shape; the JSON field must stay `likes` for outside clients. */
function likesResponse(photoId) {
return { likes: queries.likeCount.get(photoId).likeCount };
}
It called the rename "your internal rename", but it made that change itself, in the previous run. Each run starts fresh and remembers nothing; your Git history and your notes are the memory (episode 32).
Small refactors, one at a time
- Commit, and save today's answers (
before.txt). - One refactor per prompt: "only extract the photo query".
- Say the rule: "behaviour must stay the same;
check.shis how I check". - Run the check, ESLint and Prettier.
- Identical? Commit. Different? Undo or fix, then the next step.
- Never mix a refactor with a new feature or a bug fix.
$ git log --oneline
7d11169 prettier --write
755169e AI: likeCount inside, likes in the API
f75808a AI: script moved to app.js
8bfecca AI: remove unused db export
01a27a0 ESLint + Prettier
fb70b71 AI: split into src/
9895969 AI cleanup: one photo query, clear names, constants
e6213a4 Class gallery: comments, likes, days, top photos
Common mistakes (real)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
| Same logic in 4 routes | /api/top \| jq '.[0].full' → null |
Changed 3 of 4 copies | Extract one function |
| Refactor with no check | Nothing: it breaks quietly | Nobody compares | check.sh + before.txt |
| A typo in one copy | 'photo' is not defined no-undef |
Copy-paste editing | Run ESLint |
| Rename a public field | ❤ undefined |
Other programs read it | Keep public names; rename inside |
| Splitting for show | today.js: 8 lines |
More files to search | Split when it helps people |
Mini project
- Pick one of your apps. Write a
check.sh(or a small script) that calls 10–20 endpoints, including odd inputs, and saves the answers. - Find one piece of copied code; extract it into a named function. Run the check: identical?
- Name every magic number in one file.
- Add ESLint and Prettier (
npm install --save-dev eslint @eslint/js globals prettier), run them, fix what they find, run the check again. - Commit after each step.
Practice questions
- Is "fix the 500 error when there's no JSON body" a refactor?
Answer
No. It changes behaviour (500 → 400). It's a bug fix: do it as a separate change, with a test.
- Give this a good name:
const t = 15 * 60 * 1000;(used for a login lockout).
Answer
const LOCKOUT_MS = 15 * 60 * 1000; // 15 minutes
- Your check passes after a refactor, but you never tested
?n=0. What's the risk?
Answer
A behaviour change in that case would go unnoticed. A characterization check is only as good as the cases it records; include odd inputs.
- ESLint passes. Does that mean the refactor kept the behaviour?
Answer
No. A linter finds likely mistakes (undefined variables, unused code), not changed answers. Use the behaviour check for that.
- Which is safe to rename freely: a local variable, a JSON field in an API response, or a URL path?
Answer
Only the local variable. JSON fields and URL paths are read by other programs.
Quiz
Which one is a refactor?
A) Rename the JSON field likes to likeCount · B) Fix comments on photos that don't exist · C) Move the photo query into one function; same answers · D) Add a "full photo" link to every photo
Answer
C. Only C changes the structure and keeps the behaviour. A changes what the API sends, B fixes a bug, D adds a feature: all three change behaviour.
Interview questions
- What is refactoring? Restructuring code without changing its external behaviour, to make it easier to read and change.
- How do you refactor safely without good tests? First write characterization tests (save current outputs for many inputs), then refactor in small steps, comparing after each.
- What is the DRY principle? "Don't repeat yourself": keep each piece of knowledge in one place, so one change is made once.
- Linter vs formatter? A linter finds likely bugs and bad patterns; a formatter only changes layout.
- What is a breaking change, and how do you avoid one? A change that makes existing clients fail (renamed field, removed endpoint). Keep the public contract, add new fields instead of renaming, or version the API.
Glossary
| Term | Meaning (with an example from this episode) |
|---|---|
| Refactor | Changing how code is arranged inside without changing what it does (one withThumbnail() instead of four loops). |
| Behaviour | Everything the outside sees: answers, errors, status codes, odd cases. |
| Duplicated code | The same logic copied into several places (the loop in 4 routes). |
| Removing duplicates | Putting repeated logic in one place and calling it. |
| Extract a function | Moving repeated lines into one named function. |
| Naming | Choosing names that say what something is (fileVersionCache, not h). |
| Magic number | A number in code with no name (604800000). |
| Constant | A named value that doesn't change (MAX_SEARCH_LENGTH = 50). |
| Characterization check | A script that records what code does today, so changes can be detected (check.sh + before.txt). |
| Baseline | The saved "before" answers you compare against. |
diff |
A command that shows the differences between two files. |
| Splitting large files | Moving parts of a big file into smaller files by topic (src/routes/photos.js). |
| Module | A file that shares some of its code with others. |
require / module.exports |
How a CommonJS Node file imports and shares code. |
| Route | A URL + method the server answers (GET /api/top). |
| Linter | A tool that reads code without running it and warns about likely mistakes (ESLint). |
| ESLint | The common JavaScript linter. |
no-undef |
ESLint rule: a variable is used but never defined ('photo' is not defined). |
| Formatter | A tool that rewrites code layout consistently (Prettier). |
| Prettier | The common JavaScript formatter. |
| Dead code | Code nothing uses any more (the unused db export). |
| Client | Any program that calls your API (the page, Ravi's bot). |
| Breaking change | A change that makes existing clients fail (likes → likeCount). |
| JSON field | A named value in a JSON answer ("likes":2488). |
jq |
A command-line tool to pick values out of JSON (jq '.[0].full'). |
null / undefined |
"No value": JSON's null; JavaScript's undefined for a missing property. |
| Commit | A saved snapshot in Git; one per refactor step. |
| Small refactors | One change per prompt, checked and committed before the next. |
| Fresh run | Each claude -p run starts with no memory of earlier runs. |
Summary
- Copied code turns one change into four chances to forget: the fourth copy sent
null. - Refactoring keeps the behaviour and improves the structure: save the answers before, compare after.
- With a check in place, the AI's big cleanup and nine-file split were byte-for-byte identical; it even looked for the check itself.
- ESLint catches likely mistakes, Prettier fixes layout.
- The real slip: a rename of a public JSON field broke Ravi's bot (
❤ undefined), with the warning only in the last paragraph. Public names are behaviour. - Small steps: one prompt, one check, one commit.
Next episode: Working with an existing codebase.