SyntaxPilot
Courses/Vibe Coding/Lesson 15
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Vibe Coding · Lesson 15 of 40

Project: notes API with a database

databasetablerowSQL basicsSQLiteCRUD endpointsconnecting the React front endCORS error on screen and the fixdata validation

Vibe Coding: build real apps with AI · Episode 15. Every agent run below is real: Claude Code 2.1.319 (model claude-sonnet-5-5) in print mode (claude -p), on 7 November 2026, in /home/ravi/projects/notes-app (one Git repository with a server/ and a web/ folder). Server: Node.js v22.23.4, Express 5.3.0, better-sqlite3 13.0.3. Browser results come from Chromium driven by Playwright against the real dev servers. The SQL demos run in the SyntaxPilot online compiler with Python's built-in sqlite3 module. Replies are quoted exactly, shortened where marked ....

Why a database (a whiteboard vs the khata register)

Episode 14's server kept tasks in an array in memory, and a restart wiped them all.

A kirana shop Our app
a whiteboard, wiped every night memory (an array): gone when the server stops
the khata register, still there tomorrow a database: data saved on disk, organised, quick to search
a ruled page with columns: date, name, amount a table: columns, one row per entry

Tables, rows, columns and SQL

 id | title               | body
----+---------------------+-------------------------
  1 | Gas cylinder        | Book refill on the 15th
  2 | Asha birthday gift  | A cricket bat
  • A column holds one kind of value (id, title, body).
  • A row is one record (one note).
  • The primary key is the column that names exactly one row, like a roll number (id).
  • SQL (Structured Query Language) is the language for asking a database to create, read, change and delete data.

SQLite, in its own words (sqlite.org, fetched 7 Nov 2026): "an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine." Plain words: no separate database server to install; "SQLite reads and writes directly to ordinary disk files"; it's public domain and built into Python.

First SQL (run in the compiler)

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("""CREATE TABLE notes (
  id    INTEGER PRIMARY KEY AUTOINCREMENT,
  title TEXT NOT NULL,
  body  TEXT NOT NULL DEFAULT ''
)""")
db.execute("INSERT INTO notes (title, body) VALUES ('Gas cylinder', 'Book refill on the 15th')")
db.execute("INSERT INTO notes (title, body) VALUES ('Asha birthday gift', 'A cricket bat')")
db.execute("INSERT INTO notes (title) VALUES ('Call the plumber')")
for row in db.execute("SELECT id, title, body FROM notes"):
    print(row)

Output:

(1, 'Gas cylinder', 'Book refill on the 15th')
(2, 'Asha birthday gift', 'A cricket bat')
(3, 'Call the plumber', '')
SQL Means
CREATE TABLE notes (...) make a table with these columns
INTEGER PRIMARY KEY AUTOINCREMENT a whole-number id SQLite fills in for you
TEXT NOT NULL text, and a value is required
DEFAULT '' the value used when none is given
INSERT INTO notes (title, body) VALUES (...) add a row
SELECT id, title, body FROM notes read these columns from every row

The database refuses bad data

db.execute("INSERT INTO notes (body) VALUES ('no title here')")
sqlite3.IntegrityError: NOT NULL constraint failed: notes.title

A constraint is a rule the database itself enforces, whichever program sends the data.

UPDATE, DELETE, COUNT and the ? placeholder

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL DEFAULT '')")
db.executemany("INSERT INTO notes (title, body) VALUES (?, ?)",
               [("Gas cylinder", "Book refill"), ("Asha birthday gift", "A cricket bat"), ("Wi-Fi password", "Ask Ravi")])

db.execute("UPDATE notes SET body = 'Booked! No. 4417' WHERE id = 1")
db.execute("DELETE FROM notes WHERE id = 2")
print(db.execute("SELECT * FROM notes WHERE id = 1").fetchone())
print(db.execute("SELECT COUNT(*) FROM notes").fetchone())

user_input = "3 OR 1=1"          # typed by a user into a URL: /notes/3 OR 1=1
print(db.execute("SELECT title FROM notes WHERE id = " + user_input).fetchall())
print(db.execute("SELECT title FROM notes WHERE id = ?", (user_input,)).fetchall())

Output:

(1, 'Gas cylinder', 'Booked! No. 4417')
(2,)
[('Gas cylinder',), ('Wi-Fi password',)]
[]
  • WHERE id = 1 limits the change to one row. Without WHERE, UPDATE and DELETE hit every row.
  • Glued into the SQL, the user's text became WHERE id = 3 OR 1=1, which is always true: two titles leaked. This is SQL injection (Episode 28 goes deeper).
  • With a ? placeholder, the text is passed separately and treated only as a value, so nothing matches. Always use placeholders for user input.

The notes API (agent run 1)

claude -p "Build the backend for a notes app in this folder with Node.js and Express. Store the notes in a SQLite
database file so they survive a restart. Each note has an id, a title, a body and the time it was created. Make REST
endpoints to list all notes (newest first), get one, create, update and delete a note, with JSON and the right status
codes. Validate the input: the title is required and at most 100 characters, the body at most 5000. Plain JavaScript.
Then test every endpoint with curl." --allowedTools Read Write Edit Glob "Bash(npm:*)" "Bash(node:*)" "Bash(curl:*)"
"Bash(ls:*)"

Real log (shortened): npm install express better-sqlite3 → "found 0 vulnerabilities"; a shell heredoc to write db.js was refused ("Contains brace with quote character"), so it said "Nothing was written; I'll create the files with Write" and wrote db.js, app.js, server.js and .gitignore; starting the server needed approval. Reply: "The code is written, but I couldn't start the server or run the curl tests. ... So none of the endpoints have been tested yet."

better-sqlite3 is a Node.js library that lets JavaScript use SQLite.

server/db.js

const path = require('path');
const Database = require('better-sqlite3');

const file = process.env.DB_FILE || path.join(__dirname, 'notes.db');
const db = new Database(file);
db.pragma('journal_mode = WAL');

db.exec(`
  CREATE TABLE IF NOT EXISTS notes (
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    title      TEXT NOT NULL,
    body       TEXT NOT NULL DEFAULT '',
    created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
  )
`);

module.exports = db;

CREATE TABLE IF NOT EXISTS makes the table the first time and leaves it alone afterwards. created_at is filled with the current UTC time automatically. The journal_mode = WAL line is a SQLite setting for safe, fast writing.

server/app.js (part)

app.post('/notes', (req, res) => {
  const { errors, value } = validate(req.body);
  if (errors.length) return res.status(400).json({ errors });
  const info = db
    .prepare('INSERT INTO notes (title, body) VALUES (?, ?)')
    .run(value.title, value.body);
  const note = db.prepare(`${SELECT} WHERE id = ?`).get(info.lastInsertRowid);
  res.status(201).location(`/notes/${note.id}`).json(note);
});

app.delete('/notes/:id', parseId, (req, res) => {
  const info = db.prepare('DELETE FROM notes WHERE id = ?').run(req.noteId);
  if (info.changes === 0) return res.status(404).json({ error: 'Note not found' });
  res.status(204).end();
});
Endpoint SQL inside Success Errors
GET /notes SELECT ... ORDER BY created_at DESC 200
GET /notes/:id SELECT ... WHERE id = ? 200 400 bad id, 404
POST /notes INSERT ... 201 + Location 400
PUT /notes/:id UPDATE ... WHERE id = ? 200 400, 404
DELETE /notes/:id DELETE ... WHERE id = ? 204 404

Testing it (real)

$ curl -i -X POST localhost:3000/notes -H "Content-Type: application/json" \
    -d '{"title":"Gas cylinder","body":"Book refill on the 15th. Booking no. in the SMS."}'
HTTP/1.1 201 Created
Location: /notes/1
{"id":1,"title":"Gas cylinder","body":"Book refill on the 15th. Booking no. in the SMS.","createdAt":"2026-11-07T16:22:41.375Z"}

$ curl ... -d '{"title":"","body":"x"}'      → 400 {"errors":["title is required and must be a non-empty string"]}
$ curl ... --data @title101.json              → 400 {"errors":["title must be at most 100 characters"]}
$ curl -i localhost:3000/notes/abc            → 400 {"error":"id must be a positive integer"}

And the restart test that failed in Episode 14:

$ curl localhost:3000/notes
[{"id":3,"title":"Wi-Fi password for guests",...},{"id":2,"title":"Asha birthday gift",...},{"id":1,"title":"Gas cylinder",...}]
# Ctrl+C, then: node server.js
$ curl localhost:3000/notes
[{"id":3,"title":"Wi-Fi password for guests",...},{"id":2,"title":"Asha birthday gift",...},{"id":1,"title":"Gas cylinder",...}]
$ ls
app.js  db.js  node_modules  notes.db  notes.db-shm  notes.db-wal  package.json  server.js

notes.db is the database file (the -shm and -wal files are SQLite's helpers while writing). Persistence: data that outlives the program.

The React front end (agent run 2)

claude -p "My notes API is running at http://localhost:3000 (it's in ../server: GET /notes, GET /notes/:id, POST
/notes, PUT /notes/:id, DELETE /notes/:id, JSON with id, title, body, createdAt). In this folder, build a React front
end with Vite, plain JavaScript, that calls the API at http://localhost:3000: show all notes newest first, a form to add
a note (title and body), and a delete button on each note. Show a loading message and an error message if the API
fails. Don't change anything in ../server."

It wrote package.json by hand with "vite": "^5.4.11" and "react": "^18.3.1", then npm install && npm run build → "2 vulnerabilities (1 moderate, 1 high)" and vite v5.4.21 ... ✓ built in 995ms. Reply (part): "I haven't run it against your API. ... The server must allow requests from http://localhost:5173 (CORS). If the browser console shows a CORS error, either enable CORS in the server, or tell me ..."

web/src/api.js (part):

const BASE_URL = 'http://localhost:3000';

async function request(path, options) {
  const res = await fetch(`${BASE_URL}${path}`, {
    headers: { 'Content-Type': 'application/json' },
    ...options,
  });
  if (!res.ok) {
    throw new Error(`Request failed (${res.status} ${res.statusText})`);
  }
  ...

The CORS error

With both servers running, the page showed "Error: Failed to fetch", and the browser console said:

Access to fetch at 'http://localhost:3000/notes' from origin 'http://localhost:5173' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on
the requested resource.
GET http://localhost:3000/notes net::ERR_FAILED

But curl -i localhost:3000/notes gave 200 OK.

Origin, same-origin policy, CORS (a housing society's gate guard)

A housing society The browser
your flat's address: tower, floor, flat origin = scheme + host + port
the gate guard checks every visitor same-origin policy: scripts can't read other origins' responses
the intercom: "may they come up?" CORS: the server says which origins may
  • MDN (Origin): an origin is "defined by the scheme (protocol), hostname (domain), and port"; two URLs have the same origin "only when the scheme, hostname, and port all match". http://localhost:5173 and http://localhost:3000 differ in port, so they are different origins.
  • MDN (CORS): "For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts", and CORS is "an HTTP-header based mechanism that allows a server to indicate any origins ... other than its own from which a browser should permit loading resources."
  • Why the guard exists: without it, any website you visit could read pages from another site where you're logged in.
  • curl worked because CORS is a browser rule; curl has no guard.

Preflight

For requests that aren't "simple", the browser first sends a check request with the method OPTIONS (a preflight), and only sends the real request if the server approves. A request is not simple when, for example, its Content-Type is anything other than application/x-www-form-urlencoded, multipart/form-data or text/plain. The AI's api.js sends Content-Type: application/json on every request, even GET, so every request was preflighted. Our server answered the preflight with 404:

$ curl -i -X OPTIONS localhost:3000/notes -H "Origin: http://localhost:5173" \
    -H "Access-Control-Request-Method: GET" -H "Access-Control-Request-Headers: content-type"
HTTP/1.1 404 Not Found

The fix (agent run 3)

claude -p "My React front end at http://localhost:5173 can't load the notes. The browser console says: "Access to fetch
at 'http://localhost:3000/notes' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the
requested resource." curl -i -X OPTIONS localhost:3000/notes gives 404. Fix the server so the front end can use the
API. Change only what's needed."
// Allow the React dev front end to call this API (including preflight).
const ALLOWED_ORIGIN = process.env.CORS_ORIGIN || 'http://localhost:5173';
app.use((req, res, next) => {
  res.set('Access-Control-Allow-Origin', ALLOWED_ORIGIN);
  res.set('Vary', 'Origin');
  if (req.method === 'OPTIONS') {
    res.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.set('Access-Control-Allow-Headers', 'Content-Type');
    return res.status(204).end();
  }
  next();
});

A middleware is a function that runs before the routes. It allows one named origin, not * (a star means any website may call your API). The agent couldn't run its check ("So the fix is made but untested"), so we did:

$ curl -i -X OPTIONS localhost:3000/notes -H "Origin: http://localhost:5173" -H "Access-Control-Request-Method: POST"
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: http://localhost:5173
Vary: Origin
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type

In production, set CORS_ORIGIN to your real site's address.

Two more AI catches

$ npm audit
esbuild  <=0.24.2   Severity: moderate
  vite  <=6.4.3
2 vulnerabilities (1 moderate, 1 high)

$ git show --stat HEAD            (commit "React front end (AI)")
 2242 files changed, 443641 insertions(+)
  1. Old versions, again. The same mistake as Episode 12: versions written from the AI's memory. An AI doesn't remember your last project unless you tell it (Episode 32: rules files).
  2. No .gitignore in web/. node_modules/ and dist/ were committed: 2,242 files.

Agent run 4 (the real numbers in the prompt: the audit line, npm view versions vite 8.3.6, react 19.3.1, react-dom 19.3.1, @vitejs/plugin-react 6.2.1, and the file count) wrote .gitignore (node_modules/, dist/), upgraded, and reported "found 0 vulnerabilities" and vite v8.3.6 ... ✓ built in 154ms. It also warned: "the ignore rule won't remove them from git by itself ... you'll need git rm -r --cached node_modules dist".

$ git rm -r -q --cached web/node_modules web/dist && git commit ...
 2237 files changed, 478 insertions(+), 443075 deletions(-)

git rm --cached removes files from Git but keeps them on disk.

After the restart, the app loaded the notes, added "Electricity bill" at the top, and kept everything after a reload.

Validation on both sides

A 105-letter title gave only "Error: Request failed (400 Bad Request)". The server had answered {"errors":["title must be at most 100 characters"]}, but the front end threw the message away. And the form required a body (required), while the server allows an empty one.

Layer Role
the form fast, friendly hints (required, maxLength)
the server the real rule: anyone can skip the form (curl, DevTools)
the database the last line (NOT NULL)

Agent run 5:

claude -p "Two validation problems. 1) I typed a 105-character title and the page only says "Error: Request failed
(400 Bad Request)" with a Retry button. The server's response body was {"errors":["title must be at most 100
characters"]}, but the user never sees it. Show the server's error messages. 2) The form and the server disagree: the
server (../server/app.js, read it, don't change it) allows an empty body and limits the title to 100 and the body to
5000 characters, but the form requires a body and has no limits. Make the form follow the server's rules. Keep the
server as the final check. Change only what's needed in src/."

It read the server, changed api.js to show errors[] or error from the response body, removed required from the body, and added maxLength={MAX_TITLE} (100) and maxLength={MAX_BODY} (5000) with the comment "Mirror the server's limits (server/app.js); the server remains the final check." Reply: "I haven't run the app or the tests." Our test:

typed 105 letters        → the title box holds 100     (maxLength)
title + empty body       → added: "Call the electrician"
DevTools: remove maxlength, 105 letters, Add note
                         → "Error: title must be at most 100 characters"
$ git log --oneline
360c4c0 Show the server's error messages; form follows the server's rules
be7e23e Upgrade to Vite 8 + React 19, add .gitignore (npm audit: 0)
baf0734 Allow the front end's origin (CORS)
072a866 React front end (AI)
2e281b3 Notes API with SQLite (AI)

Common mistakes (real)

Mistake What you see Why Fix
Front end on :5173 calls the API on :3000 blocked by CORS policy ... No 'Access-Control-Allow-Origin' header different origin; nobody answers the preflight allow that one origin; answer OPTIONS
Access-Control-Allow-Origin: * to "make the error go away" no error any website may call your API name the allowed origin
"... WHERE id = " + userInput 3 OR 1=1 → rows leak user text becomes SQL ? placeholders
UPDATE/DELETE without WHERE every row changed no filter always write WHERE
No .gitignore in a new folder 2242 files changed node_modules and dist committed .gitignore + git rm -r --cached
Versions from the AI's memory 2 vulnerabilities old training data npm view, npm audit, upgrade
Request failed (400 Bad Request) the user can't tell what's wrong the server's message is discarded show it; same rules on both sides

Mini project

Add a search box to the notes app: GET /notes?q=gas returns notes whose title or body contains the text. Ask the AI to use LIKE ? with a placeholder (the value '%' + q + '%'), never string gluing. Then test: a normal word, an empty q, the text ' OR 1=1 --, and a 200-character q.

What a good outcome looks like

SELECT ... WHERE title LIKE ? OR body LIKE ? ORDER BY created_at DESC with the same %q% value for both; ' OR 1=1 -- finds nothing (it's just text); an empty q returns all notes; a limit on q's length returns 400 for 200 characters; the front end shows the server's message.

Practice questions

  1. What's the difference between a table, a row and a column?
Answer

A table is a set of records about one kind of thing; a row is one record; a column is one kind of value every row has.

  1. Why did the notes survive a restart this time?
Answer

They're stored in notes.db, a file on disk, instead of an array in memory.

  1. Why is "... WHERE id = " + userInput dangerous?
Answer

The user's text becomes part of the SQL (SQL injection), e.g. 3 OR 1=1 makes the condition always true. Use ? placeholders.

  1. Why did curl work while the browser was blocked?
Answer

CORS is enforced by browsers; curl doesn't apply the same-origin policy.

  1. What is a preflight request, and why did our GET need one?
Answer

An OPTIONS request the browser sends first to ask the server's permission. Our GET carried Content-Type: application/json, which isn't a simple-request content type.

  1. Why validate on the server if the form already validates?
Answer

Anyone can bypass the form (curl, DevTools, another app); the server's checks are the real rule.

Quiz

A) http://localhost:5173  and  http://localhost:3000
B) http://localhost:3000  and  https://localhost:3000
C) http://localhost:3000/notes  and  http://localhost:3000/notes/7
D) http://localhost:3000  and  http://127.0.0.1:3000

Which pair is the same origin?

Answer

C. The path is not part of the origin. A differs in port, B in scheme, D in host name.

Interview questions

  1. What is a database, and why not just save JSON in a file?
  2. Explain primary keys and constraints with an example.
  3. What is SQL injection and how do parameterized queries prevent it?
  4. What is CORS, why do browsers enforce it, and how does a server allow an origin?
  5. Why is Access-Control-Allow-Origin: * risky for an API that changes data?
  6. Where should validation live in a full-stack app?

Glossary

Term Meaning (plain words) Example
Database a program that stores data on disk, organised and searchable notes.db
Table a set of rows with the same columns notes
Row one record one note
Column one kind of value every row has title
Primary key the column that names exactly one row id
SQL the language for talking to a database SELECT * FROM notes
CREATE TABLE make a table CREATE TABLE notes (...)
INSERT add a row INSERT INTO notes ...
SELECT read rows SELECT title FROM notes
UPDATE change rows UPDATE notes SET body = ...
DELETE remove rows DELETE FROM notes WHERE id = 2
WHERE which rows WHERE id = 1
COUNT(*) how many rows (2,)
SQLite a database engine in one file, no server Python's sqlite3
better-sqlite3 a Node.js library for SQLite db.prepare(...)
Constraint a rule the database enforces NOT NULL
NOT NULL a value is required title TEXT NOT NULL
DEFAULT the value used when none is given DEFAULT ''
AUTOINCREMENT the database numbers rows for you ids 1, 2, 3
Placeholder (?) a slot filled with a value, never read as SQL WHERE id = ?
Parameterized query SQL with placeholders and separate values .run(title, body)
SQL injection user text turned into SQL commands 3 OR 1=1
CRUD Create, Read, Update, Delete POST, GET, PUT, DELETE
Persistence data that outlives the program survives a restart
Front end the part the user sees the React notes page
fetch the browser's function for HTTP requests fetch(BASE_URL + '/notes')
Origin scheme + host + port http://localhost:5173
Same-origin policy browsers block scripts from reading other origins the blocked fetch
CORS headers by which a server allows other origins Access-Control-Allow-Origin
Preflight the browser's OPTIONS "may I?" request answered with 204
OPTIONS the HTTP method used for preflight curl -X OPTIONS
Middleware a function that runs before the routes the CORS function
Validation checking data before accepting it title ≤ 100 characters
maxLength an input's character limit in the browser maxLength={100}
DevTools the browser's developer tools removing maxlength
.gitignore files Git should not track node_modules/
git rm --cached stop tracking files but keep them on disk removed 2,237 files
npm audit checks packages for known vulnerabilities "found 0 vulnerabilities"
UTC the world's reference time zone 2026-11-07T16:22:41Z

Summary

Memory forgets; a database keeps data on disk in tables of rows and columns, and SQL asks it questions. SQLite keeps a whole database in one file, and its constraints refuse bad data. User input always goes through ? placeholders (glued text leaked rows with 3 OR 1=1). The agent built a SQLite notes API that survived a restart. Its React front end hit the real CORS error: a different origin, and a preflight nobody answered. One prompt with the exact console message got a fix that allows exactly one origin. Our review also caught old library versions (again), a missing .gitignore (2,242 files committed), and a front end that hid the server's validation messages and disagreed with its rules. Validate in the form for speed, on the server for real.