SQLite in Node
Using SQLite from Node with node:sqlite and better-sqlite3, covering the synchronous API, transactions, WAL mode, and when an embedded database is right.
SQLite in Node
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- SQLite is a database in a single file, run inside your process as a library. There is no server, no connection string and no network hop, so a query costs microseconds.
- Node ships `node:sqlite`, with `DatabaseSync` for opening a file or `:memory:`, `prepare()` for statements, and `run()`, `get()` and `all()` to execute them. It is still marked as a release candidate in Node 26, so check the stability note before relying on it.
- The popular `better-sqlite3` package has the same synchronous shape and adds a `db.transaction()` helper and `db.pragma()`. Both block the event loop during a query, which is acceptable because the queries are that fast.
- Use `?` or `:name` placeholders for every value. Statement objects are reusable, so prepare once and run many times.
- Transactions are explicit: `BEGIN`, then `COMMIT`, or `ROLLBACK` on error. A multi-row insert inside one transaction is far faster than one commit per row.
- SQLite allows many readers but one writer. Turn on WAL mode (`PRAGMA journal_mode = WAL`) so readers do not block the writer, and set a `busy_timeout` so a second writer waits instead of failing with `database is locked`.
- It fits single-node apps, tools, tests, caches and edge or desktop software. It does not fit workloads that need many app servers writing to one database.
A database that is just a library
Every database in the previous lessons is a separate program you connect to. Postgres runs as a server, and your Node process talks to it over a socket, which is why pools exist. SQLite takes the opposite approach. It is a C library that reads and writes a single file. Opening a database means opening a file, and a query is a function call in your own process.
That removes a lot: no server to install, no credentials, no connection pool, no network latency. A backup is a file copy. The price is that the database lives where your process lives, and only one writer can change it at a time. For many applications that trade is a very good one. It is why SQLite sits inside phones, browsers and countless desktop apps.
Two ways to use it from Node
node:sqlite is built into Node, so there is nothing to install. On Node 26 the docs mark it stability 1.2, a release candidate, and it printed no experimental warning when I ran it. Earlier versions needed a flag, so confirm what your minimum Node version allows.
import { DatabaseSync } from 'node:sqlite';
const db = new DatabaseSync(':memory:'); // or 'app.db' for a file
db.exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER)');
const insert = db.prepare('INSERT INTO users (name, age) VALUES (?, ?)');
console.log(insert.run('Ada', 36)); // { changes: 1, lastInsertRowid: 1 }
insert.run('Bob', 41);
const byId = db.prepare('SELECT * FROM users WHERE id = ?');
console.log(byId.get(1)); // { id: 1, name: 'Ada', age: 36 }
const older = db.prepare('SELECT * FROM users WHERE age > :min ORDER BY id');
console.log(older.all({ min: 30 })); // both rows
console.log(db.prepare('SELECT * FROM users WHERE id = 99').get()); // undefined
exec() runs SQL with no result. prepare() compiles a statement you can run many times. run() is for writes and returns changes and lastInsertRowid. get() returns one row or undefined, and all() returns an array. Placeholders use ? or :name, so values never get spliced into the SQL, which is the same injection rule as with pg.
Rows come back as objects with a null prototype, so row.hasOwnProperty does not exist, and very large integers throw instead of silently losing precision. In my test, selecting 9007199254740993 threw ERR_OUT_OF_RANGE. If you need such values, read them as BigInts with the statement’s setReadBigInts(true).
better-sqlite3 is the long-standing package with the same synchronous design, and it is what the video uses. The two overlap closely, so skills transfer. It adds a transaction helper and a pragma() method, and it needs a native binary, which usually arrives prebuilt. Both versions below ran on Node 26.
import Database from 'better-sqlite3';
const db = new Database('app.db');
db.pragma('journal_mode = WAL');
const insert = db.prepare('INSERT INTO users (name) VALUES (?)');
const insertMany = db.transaction((names) => {
for (const name of names) insert.run(name);
});
insertMany(['Ada', 'Bob']); // one transaction, one commit
If anything inside insertMany throws, the whole batch rolls back. I checked this: a null in a NOT NULL column raised SQLITE_CONSTRAINT_NOTNULL, and the count stayed at 2. With node:sqlite you write the same thing yourself:
function transaction(fn) {
db.exec('BEGIN');
try { const result = fn(); db.exec('COMMIT'); return result; }
catch (err) { db.exec('ROLLBACK'); throw err; }
}
Without a transaction, each statement commits on its own and forces a disk sync. A loop of ten thousand single inserts can be orders of magnitude slower than the same loop inside one transaction.
Why synchronous is fine here
The rule from blocking vs non-blocking I/O is to avoid sync calls on a server’s hot path, because they freeze the event loop. SQLite is the deliberate exception. A query against a local file takes microseconds, so waiting for it is cheaper than the overhead of making it async. The libraries are synchronous because that is the faster design for this case.
The exception has limits. A full scan of a huge table, or a long-held transaction, blocks the loop like any other slow synchronous work. Keep queries indexed and short, and run heavy analytics somewhere else, such as a worker thread.
Concurrency: one writer
SQLite allows many readers but only one writer at a time. In the default rollback-journal mode, a writer also blocks readers. Switch to write-ahead logging and readers keep working while a write is in progress:
db.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 2000;');
I tested this with two connections to one file. In WAL mode, one connection held an open write transaction. A second connection trying to write with busy_timeout = 0 failed at once with database is locked. A reader on the second connection saw 0 rows during the write and 1 row after the commit, without blocking. With a non-zero busy_timeout, the second writer waits for the lock instead of failing. Set a timeout, and keep write transactions short.
When SQLite is the right call
It fits:
- A single-server application, internal tools, side projects, and small SaaS apps where one process owns the data.
- Tests, where an in-memory database starts in a millisecond and needs no setup. Be aware that SQLite’s SQL and type rules differ from Postgres, so it is a weak stand-in if production is Postgres. Testing backend services with real dependencies argues for the real thing where you can.
- Local state in CLIs and desktop apps, caches, queues and anything that should ship as one file.
It does not fit several app servers writing to one database, since the file lives on one machine. That case needs a client-server database, as in relational vs NoSQL databases in practice. Hosted derivatives of SQLite exist that add replication, but they are different products with their own trade-offs.
ORMs work with it too. Drizzle and Prisma both support SQLite drivers, as covered in the previous lesson.
What the video covers
Caleb Curry’s twelve-minute video is chaptered: introduction, creating a table, inserting data, retrieving all data, retrieving a single user, and building a basic API. It uses better-sqlite3, so it does not show node:sqlite, and it does not cover transactions, WAL mode or the question of when SQLite is appropriate. Those sections are carried by the prose above, and every snippet here was run on Node 26. The video’s transcript was not available, so its content is described from its chapters. The synchronous prepare, run, get and all calls it teaches work the same way in both libraries.
Where this fits
SQLite is one end of the relational spectrum, and MongoDB and Mongoose is a different model altogether.
Check yourself
Why is a synchronous database API acceptable in SQLite when it would be a bug with Postgres?
A Postgres query crosses the network and waits on another machine, so blocking the thread would stall every other request for milliseconds or more. A SQLite query runs inside your own process against a local file, usually in microseconds, so waiting for it costs less than scheduling an async callback. The risk returns only for a genuinely slow query, such as a full-table scan over a large file.
You call `insert.run()` 10,000 times in a loop with no transaction. Why is it slow, and what is the fix?
Each statement outside a transaction is its own transaction, so SQLite commits and syncs to disk for every row. Wrap the loop in `BEGIN` and `COMMIT`, or use `db.transaction()` in better-sqlite3, so there is one commit for all rows.
What does `database is locked` mean, and how do you reduce it?
Another connection holds a write lock and the one trying to write gave up immediately. Enable WAL mode so readers do not block writers, set `PRAGMA busy_timeout` so a writer waits for the lock for a while, keep write transactions short, and avoid holding one open across an `await` on slow work.
When is SQLite the wrong choice for a Node service?
When several server instances must write to the same data, because the file lives on one machine and the database cannot be shared over the network safely. Also when you need features such as fine-grained access control, server-side replication or very high write concurrency. A client-server database like Postgres is the better fit there.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.