TExcelTAD
Home › Node.js › Working with Databases

Working with Databases

Almost every back-end stores data in a database. Node can talk to all the popular ones through npm packages, and since Node 22.5 it even ships with a built-in SQLite module, node:sqlite, which is perfect for learning, small apps, tests and command-line tools.

Choosing a database

Database Type Typical Node package
SQLite SQL, single file, no server node:sqlite (built in), better-sqlite3
PostgreSQL SQL server pg, postgres
MySQL / MariaDB SQL server mysql2
MongoDB document store mongodb, mongoose
Redis in-memory key/value redis, ioredis

On top of the drivers there are ORMs and query builders such as Prisma, Drizzle, Sequelize and Knex, which map tables to JavaScript objects and generate SQL for you. Learn the plain driver first — every ORM is built on the same ideas.

Note: node:sqlite needs Node 22.5+ (behind --experimental-sqlite until 22.13, flag-free since then). It is still marked experimental, so Node prints an ExperimentalWarning to stderr the first time you use it. The examples on this page were verified with Node 24.

Opening a database and creating a table

DatabaseSync opens a file (created if missing) or, with ':memory:', a throw-away in-memory database. exec() runs SQL that doesn't return rows:

node · try it yourself
const { DatabaseSync } = require('node:sqlite');

const db = new DatabaseSync(':memory:');

db.exec(`
  CREATE TABLE books (
    id     INTEGER PRIMARY KEY AUTOINCREMENT,
    title  TEXT NOT NULL,
    author TEXT NOT NULL,
    year   INTEGER
  )
`);

const insert = db.prepare('INSERT INTO books (title, author, year) VALUES (?, ?, ?)');
const info = insert.run('Eloquent JavaScript', 'Marijn Haverbeke', 2018);
console.log(info);

insert.run('Node.js Design Patterns', 'Mario Casciaro', 2020);
insert.run('You Don\'t Know JS Yet', 'Kyle Simpson', 2020);

console.log(db.prepare('SELECT COUNT(*) AS n FROM books').get());
db.close();
{ changes: 1, lastInsertRowid: 1 }
[Object: null prototype] { n: 3 }

Rows come back as objects without a prototype (that's what [Object: null prototype] means). They behave like normal objects for reading properties and JSON.stringify.

Prepared statements and placeholders

db.prepare(sql) compiles a statement once; you can then run it many times:

Method Returns
stmt.run(...params) { changes, lastInsertRowid } — for INSERT/UPDATE/DELETE
stmt.get(...params) the first row, or undefined
stmt.all(...params) an array of all rows
stmt.iterate(...params) an iterator, row by row (for huge results)

Always pass user input as parameters (? or named :name / $name), never by building the SQL string yourself:

node · try it yourself
const { DatabaseSync } = require('node:sqlite');
const db = new DatabaseSync(':memory:');

db.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, role TEXT);
         INSERT INTO users (name, role) VALUES ('ada', 'admin'), ('bob', 'user'), ('cy', 'user');`);

const byRole = db.prepare('SELECT id, name FROM users WHERE role = :role ORDER BY name');
for (const row of byRole.all({ role: 'user' })) {
  console.log(row.id, row.name);
}

// What an attacker might type into a login form:
const evil = "nobody' OR '1'='1";

const unsafe = db.prepare(`SELECT COUNT(*) AS n FROM users WHERE name = '${evil}'`).get();
const safe = db.prepare('SELECT COUNT(*) AS n FROM users WHERE name = ?').get(evil);
console.log('string concatenation matched', unsafe.n, 'users');
console.log('parameter matched', safe.n, 'users');
db.close();
2 bob
3 cy
string concatenation matched 3 users
parameter matched 0 users

The concatenated version is an SQL injection: the attacker's quote ends the string and OR '1'='1' matches every row. With a placeholder the input is treated purely as data.

Transactions

When several statements must succeed or fail together (moving money between accounts, saving an order with its items), wrap them in a transaction:

node · try it yourself
const { DatabaseSync } = require('node:sqlite');
const db = new DatabaseSync(':memory:');
db.exec(`CREATE TABLE accounts (name TEXT PRIMARY KEY, balance INTEGER CHECK (balance >= 0));
         INSERT INTO accounts VALUES ('alice', 100), ('bob', 20);`);

const update = db.prepare('UPDATE accounts SET balance = balance + ? WHERE name = ?');

function transfer(from, to, amount) {
  db.exec('BEGIN');
  try {
    update.run(amount, to);
    update.run(-amount, from);    // violates the CHECK if the balance would go negative
    db.exec('COMMIT');
    console.log(`moved ${amount} from ${from} to ${to}`);
  } catch (err) {
    db.exec('ROLLBACK');
    console.log(`transfer of ${amount} failed: ${err.message}`);
  }
}

const show = () => console.log(db.prepare('SELECT name, balance FROM accounts ORDER BY name').all()
  .map((r) => `${r.name}=${r.balance}`).join(' '));

transfer('alice', 'bob', 30);
show();
transfer('bob', 'alice', 500);
show();
db.close();
moved 30 from alice to bob
alice=70 bob=50
transfer of 500 failed: CHECK constraint failed: balance >= 0
alice=70 bob=50

Bob was credited first in the failed transfer, but the ROLLBACK undid it — the data is never left half-updated.

Talking to a database server

Server databases like PostgreSQL work the same way conceptually, but the driver is asynchronous and you usually use a connection pool. With the pg package (not installable here) the code looks like this:

js
import pg from 'pg';

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });

const { rows } = await pool.query(
  'SELECT id, title FROM books WHERE year >= $1 ORDER BY year',
  [2019],
);
console.log(rows);

await pool.end();

Tip: Create one pool when your app starts and reuse it for every request. Opening a fresh connection per request is slow and can exhaust the server's connection limit.

Test yourself

Which module gives Node a built-in SQLite database (Node 22.5+)?

  1. node:sql
  2. node:sqlite
  3. node:db
  4. sqlite3

Why should user input be passed as ? parameters instead of concatenated into the SQL string?

  1. It is faster to type
  2. It prevents SQL injection because input is treated as data
  3. SQLite does not support strings
  4. Concatenation is not allowed in JavaScript

What does ROLLBACK do inside a transaction?

  1. Repeats the last statement
  2. Undoes all changes made since BEGIN
  3. Deletes the table
  4. Closes the database