Course map
Stage 1: App Router Foundations
Stage 2: The Rendering Model
Stage 3: Data, Caching and Mutations
Stage 4: Full-Stack Next.js
Stage 5: Production and Specialization

Part 16 / Stage 4

Database integration

Goal: Replace an in-memory JavaScript array with a real, persistent SQLite database, through a small data-access layer the rest of the app never bypasses — called from a Server Component, a Server Action, and a Route Handler alike, and still there after the server itself restarts. Built as Mandi Fresh's guestbook: a better-sqlite3-backed note board visitors can read and post to. Time: ~7 h · Level: finished Part 15 (An auth pattern) Verified against: Next.js 16.4.6 / React 19.3.0, cacheComponents: true + partialPrefetching: true, better-sqlite3 13.2.0 — installed for real (npm install better-sqlite3), every example below actually run against this harness.

What you will learn

  • Why better-sqlite3 (not an async driver) was the right choice here, with the installed package's own benchmark numbers and design rationale, not just an assertion
  • Opening one shared SQLite connection per process, enabling WAL mode, and running a schema migration at module load
  • A small data-access layer (DAL): one module that owns every db.prepare(...) call, with no raw SQL anywhere else in the app
  • Calling the same DAL from three different places — a Server Component's render, a Server Action's write, and a Route Handler's GET — and what changes (and what doesn't) between them
  • Combining a synchronous database read with Part 10's "use cache" and Part 12's updateTag, for real
  • The installed docs' own named gotcha for synchronous drivers under Cache Components — reproduced for real, not just quoted
  • Actually restarting the server and confirming the data survives — not asserted, observed

Topics in this part

Practice

Several exercises below temporarily edit a real file in this harness (app/api/mandi/guestbook/route.ts) or run a standalone node -e script against a scratch SQLite file — each one says exactly which, and each one restores/removes what it changed before moving on. Delete app/mandi/guestbook/mandi-guestbook.sqlite* (all three files — the main db, -shm, and -wal) before starting fresh, and again once you're done, so your own guestbook starts empty for the next exercise.


Exercise 1: A transaction really is atomic — a failure rolls back everything, not just the failed row

Scenario: better-sqlite3's own API includes db.transaction(fn). Confirm it behaves like a real transaction, not just "run these one after another." What to do: In a scratch node -e script (not this harness's actual guestbook, to avoid touching its real data), create an in-memory database, wrap three inserts in db.transaction(...), and have the batch throw partway through (after one of the inserts already ran). Check the row count afterward.

Sample output (run for real, standalone node -e, against a scratch in-memory db):

$ node -e "... insertMany(['d','bad','e']) where the loop throws right after inserting 'd' and before 'e' ..."
caught: boom
{ c: 3 }   // still 3 — the pre-existing rows from an earlier successful transaction; the failed batch added none

💡 Hint: Even though 'd' was successfully inserted before the throw, the row count afterward shows it never happened — db.transaction(fn) wraps the whole function in BEGIN/COMMIT, and an exception anywhere inside triggers a ROLLBACK of everything the transaction did, not just the statement that threw.


Exercise 2: The "frozen at build time" gotcha, reproduced with real stale data

Scenario: Part 16's README section 6 showed the route table symbol (○ vs ƒ) for a Route Handler with and without connection(). Prove it with actual data, not just the symbol — a build-time snapshot that never updates, even while the real database keeps changing underneath it. What to do: Temporarily replace app/api/mandi/guestbook/route.ts with the no-connection() version (just listEntries(), no await connection()). Seed the database with one entry before next build, build, start the server, confirm the route returns that entry, then insert a second entry directly into the database (a separate script, while the server keeps running — no rebuild), and request the route again.

Sample output (run for real against this course's harness):

$ curl -s http://localhost:PORT/api/mandi/guestbook   # right after build+start
{"entries":[{"id":1,"name":"Seed Visitor","message":"present at build time", ...}]}
# (a second entry, "Late Visitor", inserted directly into the .sqlite file here, server still running, no rebuild)
$ curl -s http://localhost:PORT/api/mandi/guestbook   # same running server, no rebuild
{"entries":[{"id":1,"name":"Seed Visitor","message":"present at build time", ...}]}

💡 Hint: The second request is identical to the first — "Late Visitor" never appears, no matter how many more times you request it, because the entire response was computed once, at build time, and is being served from a static artifact that has no idea the database changed. Restoring the connection() version and rebuilding fixes it immediately (confirmed in the README's own section 6). Delete the scratch .sqlite* files and restore the real route file afterward.


Exercise 3: SQL injection — reproduced on a vulnerable version, blocked on the real one

Scenario: This part's lib/entries.ts always uses ? placeholders. Confirm, concretely, what goes wrong without them. What to do: In a scratch node -e script, build two lookup functions against the same in-memory table — one using string concatenation ("... WHERE name = '" + name + "'"), one using a prepared statement with a ? placeholder — and call both with the classic x' OR '1'='1 payload.

Sample output (run for real, standalone):

$ node -e "... findVulnerable(\"x' OR '1'='1\") ..."
[ { id: 1, name: 'Priya' }, { id: 2, name: 'Admin' } ]
$ node -e "... findSafe.all(\"x' OR '1'='1\") ..."
[]

💡 Hint: The concatenated version returns every row in the table, including one the attacker's input string never named — the payload closed the quoted string early and appended a condition that's always true. The parameterized version treats the exact same string as a single literal value to compare against, never as part of the SQL itself, and correctly returns nothing (no user is actually named x' OR '1'='1). This is the entire reason lib/entries.ts's two prepared statements use ? for every value, with no exceptions.


Exercise 4: :memory: — the opposite of section 5's persistence proof

Scenario: Section 5 proved the real guestbook's file-based database survives a restart. Confirm the contrapositive: an in-memory database does not, because there's no file for a new connection to reopen. What to do: In a scratch node -e script, open new Database(':memory:'), create a table, insert a row, and close it (simulating a server stopping). In a second, separate node -e invocation, open another new Database(':memory:') and try to read the same table.

Sample output (run for real, standalone, two separate node -e processes):

$ node -e "... insert into :memory: db, then console.log the rows, then db.close() ..."
before close: [ { id: 1, n: 'will vanish' } ]
$ node -e "... new Database(':memory:') in a brand-new process, try to read the same table ..."
after reopen, error (table does not exist): no such table: t

💡 Hint: The second process's :memory: database is a completely different, empty database — :memory: never touches disk at all, so there is nothing for a later connection (in this exercise, a separate process; in a real app, a restarted server) to reopen. This is exactly why harness/app/mandi/guestbook/lib/db.ts uses a real file path, not :memory: — section 5's whole persistence guarantee depends on it.


Exercise 5: The WAL side files outlive a kill — and the data is still correct afterward

Scenario: lib/db.ts never calls db.close() — the connection stays open for the server process's entire life. Check what that means for the -wal/-shm files when the process is killed abruptly, and whether the data is still intact afterward. What to do: Start this harness for real, post one guestbook entry, confirm the -wal/-shm files exist on disk while the server is running, then kill the server process directly (not a graceful shutdown) and check the same files immediately afterward. Finally, open a brand-new connection to the same file and read the data back.

Sample output (run for real against this course's harness):

$ ls -la app/mandi/guestbook/mandi-guestbook.sqlite*   # server still running
mandi-guestbook.sqlite      mandi-guestbook.sqlite-shm      mandi-guestbook.sqlite-wal
$ kill <server-pid>
$ ls -la app/mandi/guestbook/mandi-guestbook.sqlite*   # immediately after
mandi-guestbook.sqlite      mandi-guestbook.sqlite-shm      mandi-guestbook.sqlite-wal
$ node -e "... open a new connection, SELECT * FROM guestbook_entries ..."
[ { id: 1, name: 'Test', message: 'checking wal files', created_at: '...' } ]

💡 Hint: The -wal/-shm files are still there after the kill — nothing in this harness's code ever asked SQLite to checkpoint the write-ahead log back into the main file and clean them up, and an abrupt kill doesn't trigger that automatically either. That's not data loss, though: the last line proves a brand-new connection reads the exact same row back correctly — SQLite transparently merges the WAL into what a reader sees, whether or not it's been checkpointed into the main file yet. Delete the scratch .sqlite* files afterward so your guestbook starts empty again.


Next

🎉 Stage 4 done! Go to project-quickcart for the capstone.

Show the solutions for Part 16 (5 files)

solutions/ex01.md

# Solution to Exercise 1

```js
// scratch node -e script, not part of this harness
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('CREATE TABLE t (id INTEGER PRIMARY KEY, n TEXT)');
const insert = db.prepare('INSERT INTO t (n) VALUES (?)');

const insertMany = db.transaction((names) => {
  for (const name of names) insert.run(name);
});
insertMany(['a', 'b', 'c']);
console.log(db.prepare('SELECT count(*) as c FROM t').get()); // { c: 3 }

try {
  db.transaction((names) => {
    for (const name of names) {
      insert.run(name);
      if (name === 'bad') throw new Error('boom');
    }
  })(['d', 'bad', 'e']);
} catch (e) {
  console.log('caught:', e.message);
}
console.log(db.prepare('SELECT count(*) as c FROM t').get());
```

**Run for real:**
```text
$ node -e "...(script above)..."
{ c: 3 }
caught: boom
{ c: 3 }
```

The count stays at `3` both before and after the failed batch — `'d'`
was genuinely inserted (its `INSERT` ran, inside the transaction) before
the `throw`, but `db.transaction(fn)` wraps the whole callback in a real
`BEGIN`/`COMMIT`/`ROLLBACK`: any exception thrown inside it rolls back
every statement the transaction ran, not just the one that failed. This
is what makes `db.transaction(...)` the right tool for "insert N related
rows, and if any one of them fails, none of them should exist" — exactly
the kind of batch write the QuickCart capstone's checkout flow needs for
cart-to-order conversion.

solutions/ex02.md

# Solution to Exercise 2

```ts
// app/api/mandi/guestbook/route.ts (temporarily reverted — no connection())
import { listEntries } from "../../../mandi/guestbook/lib/entries";

export async function GET() {
  const entries = listEntries();
  return Response.json({ entries });
}
```

**Seeded the database with one row before building, run for real against
this harness:**
```text
$ node -e "...insert ('Seed Visitor', 'present at build time') into guestbook_entries..."
$ npm run build
...
├ ○ /api/mandi/guestbook
$ npm run start -p PORT
$ curl -s http://localhost:PORT/api/mandi/guestbook
{"entries":[{"id":1,"name":"Seed Visitor","message":"present at build time","createdAt":"2026-12-01T12:39:16.012Z"}]}
```

**Inserted a second row directly into the same `.sqlite` file, server
still running, no rebuild:**
```text
$ node -e "...insert ('Late Visitor', 'arrived after the build')..."
$ curl -s http://localhost:PORT/api/mandi/guestbook
{"entries":[{"id":1,"name":"Seed Visitor","message":"present at build time","createdAt":"2026-12-01T12:39:16.012Z"}]}
```

Identical response — "Late Visitor" never appears, confirmed by
requesting it again afterward with the same result. The entire JSON body
was computed exactly once, during `next build`, and `next start` has
been serving that frozen artifact ever since; the running server never
re-runs `listEntries()` for this route at all. Restoring the real route
file (with `await connection()`) and rebuilding immediately fixes this —
the README's own section 6 shows the same route reclassified `ƒ` and
serving live data again. Deleted the scratch `.sqlite*` files afterward.

solutions/ex03.md

# Solution to Exercise 3

```js
// scratch node -e script, not part of this harness
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');
db.prepare('INSERT INTO users (name) VALUES (?)').run('Priya');
db.prepare('INSERT INTO users (name) VALUES (?)').run('Admin');

function findVulnerable(name) {
  return db.prepare("SELECT * FROM users WHERE name = '" + name + "'").all();
}
const findSafe = db.prepare('SELECT * FROM users WHERE name = ?');

console.log('normal lookup:', findVulnerable('Priya'));
console.log('injection attempt:', findVulnerable("x' OR '1'='1"));
console.log('same payload, parameterized:', findSafe.all("x' OR '1'='1"));
```

**Run for real:**
```text
$ node -e "...(script above)..."
normal lookup: [ { id: 1, name: 'Priya' } ]
injection attempt: [ { id: 1, name: 'Priya' }, { id: 2, name: 'Admin' } ]
same payload, parameterized: []
```

The string-concatenation version returns **both** rows for the payload
`x' OR '1'='1` — the closing `'` in the payload ends the intended quoted
string early, and `OR '1'='1'` turns the `WHERE` clause into something
always true, leaking every row regardless of name. The prepared
statement treats the identical string as one opaque value bound to the
`?` placeholder — SQLite compares it literally against the `name`
column, finds no match (no user is actually named that string), and
correctly returns nothing. This is why every query in
`app/mandi/guestbook/lib/entries.ts` uses `?` placeholders exclusively,
with no string-built SQL anywhere.

solutions/ex04.md

# Solution to Exercise 4

**First process — write, read, close:**
```js
// scratch node -e script, invocation 1
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('CREATE TABLE t (id INTEGER PRIMARY KEY, n TEXT)');
db.prepare('INSERT INTO t (n) VALUES (?)').run('will vanish');
console.log('before close:', db.prepare('SELECT * FROM t').all());
db.close();
```
```text
$ node -e "...(script above)..."
before close: [ { id: 1, n: 'will vanish' } ]
```

**Second, separate process — a brand-new `:memory:` database:**
```js
// scratch node -e script, invocation 2 (a different process)
const Database = require('better-sqlite3');
const db2 = new Database(':memory:');
try {
  console.log('after reopen:', db2.prepare('SELECT * FROM t').all());
} catch (e) {
  console.log('after reopen, error:', e.message);
}
```
```text
$ node -e "...(script above)..."
after reopen, error: no such table: t
```

The second process's `:memory:` database doesn't even have the `t`
table — it's a completely separate, empty database that happens to use
the same special `:memory:` name, not a resumed version of the first
one. `:memory:` never writes to disk at all, so there's nothing left for
a later connection (here, a new process; in a real app, a restarted
server) to reopen. `app/mandi/guestbook/lib/db.ts` deliberately uses a
real file path for exactly this reason — it's what makes the README's
own section 5 persistence proof (data surviving an actual server
restart) possible at all.

solutions/ex05.md

# Solution to Exercise 5

**Run for real against this harness:**
```text
$ npm run build && npm run start -p PORT
$ curl -s http://localhost:PORT/mandi/guestbook -o page.html   # read the real $ACTION_ID_... field
$ curl -s -X POST http://localhost:PORT/mandi/guestbook -F '$ACTION_ID_...=' -F 'name=Test' -F 'message=checking wal files'
$ ls -la app/mandi/guestbook/mandi-guestbook.sqlite*   # server still running
-rw-r--r--  ...  mandi-guestbook.sqlite
-rw-r--r--  ...  mandi-guestbook.sqlite-shm
-rw-r--r--  ...  mandi-guestbook.sqlite-wal
$ kill <server-pid>   # a plain kill, no graceful-shutdown handling in this code at all
$ ls -la app/mandi/guestbook/mandi-guestbook.sqlite*   # immediately after
-rw-r--r--  ...  mandi-guestbook.sqlite
-rw-r--r--  ...  mandi-guestbook.sqlite-shm
-rw-r--r--  ...  mandi-guestbook.sqlite-wal
$ node -e "const db = require('better-sqlite3')('app/mandi/guestbook/mandi-guestbook.sqlite'); console.log(db.prepare('SELECT * FROM guestbook_entries').all());"
[ { id: 1, name: 'Test', message: 'checking wal files', created_at: '2026-12-01T12:40:29.955Z' } ]
```

All three files (the main database plus `-shm`/`-wal`) are still present
immediately after the `kill` — nothing in `lib/db.ts` ever called
`db.close()` or asked SQLite to checkpoint, and a plain `kill` doesn't
trigger that cleanup on its own. That is **not** data loss, though: the
final command opens a completely fresh connection and reads the exact
row back correctly. SQLite's WAL mode is designed so a reader always
sees the true current state regardless of whether the write-ahead log
has been checkpointed into the main file yet — the side files are an
implementation detail of *how* that durability is achieved, not a sign
that anything is pending or at risk. Deleted the scratch `.sqlite*`
files afterward so the guestbook starts empty again.

Common mistakes

Mistake Why it is wrong Fix
Opening a new Database(...) connection inside every function that needs one Defeats the point of a single-process, single-writer database — and Next.js's own module caching already gives you a shared instance for free if you open it once at module scope Open the connection once (lib/db.ts), export it, and let every DAL function reuse it
Scattering db.prepare(...)/raw SQL across pages, actions, and route handlers Exactly the "raw queries scattered through components" the stage plan warns against — no single place to review, test, or change the schema from Centralize every query in one DAL module (lib/entries.ts), called by name from everywhere else
Assuming a synchronous better-sqlite3 read is automatically "dynamic" under Cache Components because it looks like it talks to a database Section 6 reproduced the opposite: with no runtime API read, the query can run once at build time and freeze forever, with the route table itself confirming ○ Call connection() before the query if nothing else already forces the route dynamic (a cached wrapper with cacheTag, like section 4's page, is the other valid fix)
Reaching for revalidatePath after a write to data behind a cacheTag-tagged "use cache" read No same-response guarantee, and it's targeting the wrong mechanism — the data has a real tag, Part 12's updateTag is what targets it Use updateTag with the matching tag string inside the Server Action that wrote the data
Assuming in-memory state (every earlier part's lib/*.ts modules) and a real database behave the same way across a restart Part 9–15's data resets to its seeded values on every next dev/next start restart; a real database does not Test persistence explicitly, the way section 5 did — stop the process, start a new one, and read the same file back

Quick recap

  • better-sqlite3 was chosen with the same npm-evidence standard DESIGN-NOTES.md already used for Prisma — a stable latest tag — and its own README states, with real benchmark numbers, why a synchronous API outperforms an async wrapper for a single-writer, file-based database.
  • One shared connection, opened once per process with WAL mode on, and a migration (CREATE TABLE IF NOT EXISTS) run at module load — not per request.
  • A small DAL (lib/entries.ts) is the only file that writes SQL; the Server Component, the Server Action, and the Route Handler all call it by name.
  • A cached read ("use cache" + cacheTag) and updateTag on write compose with a synchronous database exactly like they did with the in-memory data in Parts 10–12 — nothing about the caching model changes because the data source did.
  • Cache Components can silently freeze a synchronous database read into a build-time artifact if nothing else forces the route dynamic — reproduced for real, fixed with connection(), the installed docs' own named solution for "synchronous database drivers."
  • Data written to this part's SQLite file was still there after the server process that wrote it was fully stopped and a new one started — verified directly, not assumed.

Checklist

  • I installed better-sqlite3 for real and can state, from its own README, why its synchronous API is the better-performing choice for this use case, not merely the simpler one.
  • I wrote a small DAL with prepared statements, and every other file in this harness's guestbook calls it by name instead of writing its own SQL.
  • I called the same DAL function from a Server Component, a Server Action, and a Route Handler, and can point to the one line that differs in each (cached wrapper, updateTag, connection()).
  • I reproduced the "frozen at build time" gotcha for a synchronous database read with no runtime API access, confirmed it in a real next build route table, and fixed it with connection().
  • I actually stopped the server process, started a new one, and confirmed the same data was still on disk — not assumed from the code alone.

Search the guide