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 / Topic 2 of 6

One connection, WAL mode, a migration at module load

// harness/app/mandi/guestbook/lib/db.ts (excerpt)
import Database from "better-sqlite3";

const db = new Database(DB_PATH);
db.pragma("journal_mode = WAL");
db.exec(`CREATE TABLE IF NOT EXISTS guestbook_entries (...)`);

export { db };

This module runs once per process — Node's own module cache means every other file that imports { db } gets the same open connection, not a fresh one. journal_mode = WAL is the installed package's own documented recommendation ("it is generally important to set the WAL pragma for performance reasons") — confirmed on disk after this harness's own first write, where SQLite keeps its write-ahead log as separate files next to the main database:

$ ls app/mandi/guestbook/
mandi-guestbook.sqlite  mandi-guestbook.sqlite-shm  mandi-guestbook.sqlite-wal

All three are gitignored by this repo's root *.sqlite rule (confirmed with git check-ignore -v) — real data, never committed.

Done here? The practice set for Part 16 — including the solutions — is on the part page.

Search the guide