SQLite

suggest change

SQLite is a zero-configuration, serverless, file-based relational database engine. In Node.js, SQLite is widely used for desktop applications (Electron), CLI tools, local caching, edge compute, and high-speed unit testing.

Modern Node.js provides two primary ways to interact with SQLite:

  1. Built-in node:sqlite module: Native SQLite support bundled directly into Node.js (Node 22.5+).
  2. better-sqlite3: The industry-standard, high-performance synchronous driver for production workloads.

1. Using Node's Built-in node:sqlite Module (Node 22.5+)

Starting with Node.js v22.5.0, Node includes built-in support for SQLite via the node:sqlite module using the synchronous DatabaseSync class (it required the --experimental-sqlite flag until v22.13.0 / v23.4.0).

import { DatabaseSync } from 'node:sqlite';

// Open an on-disk database file or an in-memory database using ':memory:'
const db = new DatabaseSync('./app.db');

// Execute DDL schema creation
db.exec(`
  CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    email TEXT UNIQUE NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  )
`);

// Insert records using prepared statements
const insertStmt = db.prepare('INSERT OR IGNORE INTO users (name, email) VALUES (?, ?)');
insertStmt.run('Alice Smith', 'alice@example.com');
insertStmt.run('Bob Jones', 'bob@example.com');

// Query a single record
const selectOneStmt = db.prepare('SELECT * FROM users WHERE email = ?');
const user = selectOneStmt.get('alice@example.com');
console.log('User found:', user);

// Query multiple records
const selectAllStmt = db.prepare('SELECT id, name, email FROM users ORDER BY id ASC');
const allUsers = selectAllStmt.all();
console.table(allUsers);

// Always close the database handle when finished
db.close();

2. Using better-sqlite3 (Production Standard)

better-sqlite3 is the fastest and most feature-complete SQLite library in the Node ecosystem.

Installation

npm install better-sqlite3

Complete CRUD and Transactions Example

import Database from 'better-sqlite3';

// Connect to on-disk database
const db = new Database('production.db', { verbose: console.log });

// Enable Write-Ahead Logging (WAL) for superior concurrency and write performance
db.pragma('journal_mode = WAL');

// 1. Create table
db.exec(`
  CREATE TABLE IF NOT EXISTS products (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    sku TEXT UNIQUE NOT NULL,
    name TEXT NOT NULL,
    price REAL NOT NULL,
    stock INTEGER NOT NULL DEFAULT 0
  )
`);

// 2. Prepared statements with named parameters
const insertProduct = db.prepare(`
  INSERT OR IGNORE INTO products (sku, name, price, stock)
  VALUES (@sku, @name, @price, @stock)
`);

const getProductBySku = db.prepare('SELECT * FROM products WHERE sku = ?');
const updateStock = db.prepare('UPDATE products SET stock = stock - ? WHERE id = ?');

// 3. Atomic Transactions
// Wrap multi-step operations in a transaction to guarantee ACID integrity
const processPurchase = db.transaction((productId, quantity) => {
  const info = updateStock.run(quantity, productId);
  if (info.changes === 0) {
    throw new Error('Product not found or stock update failed');
  }
  return { success: true, updatedRows: info.changes };
});

// Execute insert
insertProduct.run({
  sku: 'PROD-001',
  name: 'Ergonomic Keyboard',
  price: 99.99,
  stock: 25
});

// Execute query
const product = getProductBySku.get('PROD-001');
console.log('Product retrieved:', product);

// Execute transaction
processPurchase(product.id, 2);
console.log('Stock reduced successfully.');

db.close();

3. In-Memory SQLite for Automated Unit Testing

In-memory SQLite databases (:memory:) are wiped when the connection closes, making them fast and clean for unit test suites (e.g. with Vitest or Jest):

import Database from 'better-sqlite3';

export function createTestDatabase() {
  const db = new Database(':memory:');
  db.exec(`
    CREATE TABLE accounts (
      id INTEGER PRIMARY KEY,
      balance INTEGER NOT NULL
    );
    INSERT INTO accounts (id, balance) VALUES (1, 500);
  `);
  return db;
}

// In test file:
const db = createTestDatabase();
const account = db.prepare('SELECT * FROM accounts WHERE id = 1').get();
console.assert(account.balance === 500, 'Balance mismatch');
db.close();

4. Best Practices for SQLite in Node.js

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents