languages
November 10, 2026 · 9 min read · 25 views

Node.js 24: Native SQLite Support, Worker Threads Improvements, and V8 12.2

Node.js 24 ships native SQLite support, enhanced Worker Threads performance, and V8 12.2. A deep dive into what's new, migration paths, and practical examples for developers.

Node.js 24 is Here: What You Need to Know

Node.js 24 was released on April 15, 2025, bringing significant performance improvements, native SQLite integration, and critical enhancements to Worker Threads. This release represents a major step forward for backend developers building data-intensive applications, microservices, and real-time systems.

While Node.js 24 enters the Active LTS phase with support until April 2027, the headline features—particularly built-in SQLite without external dependencies and streamlined concurrency patterns—make this a release worth upgrading for production workloads.

Native SQLite Support: Embedded Databases Without Dependencies

Why This Matters

Previously, using SQLite in Node.js required third-party bindings like better-sqlite3 or sql.js, introducing native module compilation, security surface area, and dependency management overhead. Node.js 24 ships with --sqlite experimental flag support, enabling developers to use SQLite directly through the Node.js runtime.

This is transformative for:

  • Edge computing and serverless: Lightweight data persistence without bloated dependencies
  • Desktop apps with Electron: Faster startup times and reduced bundle size
  • Offline-first applications: Seamless sync between local SQLite and remote APIs
  • Development and testing: Instant database setup without Docker or separate services

Getting Started with Native SQLite

To enable SQLite in Node.js 24, use the experimental flag when running your application:

node --sqlite app.js

Once enabled, you can import and use SQLite through the built-in node:sqlite module:

const { DatabaseSync } = require('node:sqlite');

// Create or open an in-memory database
const db = new DatabaseSync(':memory:');

// Execute SQL statements
db.exec(`
  CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT UNIQUE,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  )
`);

// Prepare a statement for repeated use
const insertUser = db.prepare(`
  INSERT INTO users (name, email) VALUES (?, ?)
`);

// Execute with parameter binding
insertUser.run('Alice Chen', '[email protected]');
insertUser.run('Bob Smith', '[email protected]');

// Query data
const getAllUsers = db.prepare('SELECT * FROM users');
const users = getAllUsers.all();

console.log(users);
// Output:
// [
//   { id: 1, name: 'Alice Chen', email: '[email protected]', created_at: '...' },
//   { id: 2, name: 'Bob Smith', email: '[email protected]', created_at: '...' }
// ]

// Single row queries
const findUser = db.prepare('SELECT * FROM users WHERE id = ?');
const user = findUser.get(1);
console.log(user); // { id: 1, name: 'Alice Chen', ... }

// Transactions for data integrity
const transfer = () => {
  db.exec('BEGIN');
  try {
    db.prepare('UPDATE users SET balance = balance - 10 WHERE id = 1').run();
    db.prepare('UPDATE users SET balance = balance + 10 WHERE id = 2').run();
    db.exec('COMMIT');
  } catch (err) {
    db.exec('ROLLBACK');
    throw err;
  }
};

transfer();

Real-World Example: User Session Store

Here’s a practical example of building a lightweight session store with native SQLite:

const { DatabaseSync } = require('node:sqlite');
const crypto = require('crypto');

class SessionStore {
  constructor(dbPath = ':memory:') {
    this.db = new DatabaseSync(dbPath);
    this.initSchema();
  }

  initSchema() {
    this.db.exec(`
      CREATE TABLE IF NOT EXISTS sessions (
        id TEXT PRIMARY KEY,
        user_id INTEGER NOT NULL,
        data TEXT NOT NULL,
        expires_at DATETIME NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
      );
      
      CREATE INDEX IF NOT EXISTS idx_expires_at ON sessions(expires_at);
    `);
  }

  createSession(userId, data = {}) {
    const sessionId = crypto.randomUUID();
    const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours
    
    const insert = this.db.prepare(`
      INSERT INTO sessions (id, user_id, data, expires_at) 
      VALUES (?, ?, ?, ?)
    `);
    
    insert.run(sessionId, userId, JSON.stringify(data), expiresAt.toISOString());
    return sessionId;
  }

  getSession(sessionId) {
    const query = this.db.prepare(`
      SELECT * FROM sessions 
      WHERE id = ? AND expires_at > datetime('now')
    `);
    
    const session = query.get(sessionId);
    if (!session) return null;
    
    return {
      id: session.id,
      userId: session.user_id,
      data: JSON.parse(session.data),
      createdAt: session.created_at
    };
  }

  updateSession(sessionId, data) {
    const update = this.db.prepare(`
      UPDATE sessions SET data = ? WHERE id = ?
    `);
    
    update.run(JSON.stringify(data), sessionId);
  }

  deleteSession(sessionId) {
    const del = this.db.prepare('DELETE FROM sessions WHERE id = ?');
    del.run(sessionId);
  }

  cleanupExpiredSessions() {
    const del = this.db.prepare(
      "DELETE FROM sessions WHERE expires_at < datetime('now')"
    );
    const result = del.run();
    return result.changes; // Number of rows deleted
  }
}

// Usage
const store = new SessionStore();
const sessionId = store.createSession(42, { role: 'admin', theme: 'dark' });
console.log('Session created:', sessionId);

const session = store.getSession(sessionId);
console.log('Retrieved session:', session);

store.updateSession(sessionId, { ...session.data, theme: 'light' });

const cleaned = store.cleanupExpiredSessions();
console.log(`Cleaned up ${cleaned} expired sessions`);

Performance Characteristics

Native SQLite in Node.js 24 is synchronous, which means it blocks the event loop. This is intentional—SQLite is designed for fast, embedded queries. For I/O-intensive applications, consider:

  • Keeping queries small and indexed: Avoid full table scans
  • Using Worker Threads for background operations: Keep the main thread responsive
  • Batching writes: Use transactions to group operations

Enhanced Worker Threads Performance

What’s Improved

Node.js 24 refines the Worker Threads implementation with:

  • Faster message serialization for large data transfers
  • Reduced memory overhead per worker
  • Improved thread pooling for CPU-bound tasks

Building a Thread Pool for Heavy Computations

Here’s a practical example of using Worker Threads to offload CPU-intensive work:

// worker.js
const { parentPort } = require('worker_threads');

parentPort.on('message', (task) => {
  try {
    // Simulate heavy computation
    let result = 0;
    for (let i = 0; i < task.count; i++) {
      result += Math.sqrt(i) * Math.sin(i);
    }
    
    parentPort.postMessage({
      taskId: task.id,
      status: 'success',
      result,
      duration: Date.now() - task.startTime
    });
  } catch (err) {
    parentPort.postMessage({
      taskId: task.id,
      status: 'error',
      error: err.message
    });
  }
});
// main.js
const { Worker } = require('worker_threads');
const os = require('os');

class ThreadPool {
  constructor(workerScript, poolSize = os.cpus().length) {
    this.workers = [];
    this.taskQueue = [];
    this.activeWorkers = new Map();
    
    for (let i = 0; i < poolSize; i++) {
      const worker = new Worker(workerScript);
      
      worker.on('message', (message) => {
        const resolve = this.activeWorkers.get(message.taskId);
        if (resolve) {
          resolve(message);
          this.activeWorkers.delete(message.taskId);
        }
        
        // Process next queued task
        if (this.taskQueue.length > 0) {
          const nextTask = this.taskQueue.shift();
          this.executeOnWorker(worker, nextTask);
        }
      });
      
      this.workers.push(worker);
    }
  }
  
  executeOnWorker(worker, task) {
    return new Promise((resolve) => {
      this.activeWorkers.set(task.id, resolve);
      worker.postMessage({ ...task, startTime: Date.now() });
    });
  }
  
  async run(task) {
    const availableWorker = this.workers.find(
      (w) => !this.activeWorkers.has(w.taskId)
    );
    
    task.id = Math.random().toString(36).slice(2, 11);
    
    if (availableWorker) {
      return this.executeOnWorker(availableWorker, task);
    } else {
      // Queue the task if all workers are busy
      return new Promise((resolve) => {
        this.taskQueue.push(task);
        // Note: In production, add timeout logic
      });
    }
  }
  
  terminate() {
    return Promise.all(this.workers.map((w) => w.terminate()));
  }
}

// Usage
const pool = new ThreadPool('./worker.js', 4);

(async () => {
  const tasks = [
    { count: 1000000 },
    { count: 2000000 },
    { count: 1500000 },
    { count: 800000 }
  ];
  
  const results = await Promise.all(
    tasks.map((task) => pool.run(task))
  );
  
  console.log('Results:', results);
  // Results: [
  //   { taskId: 'abc123', status: 'success', result: 123456.78, duration: 145 },
  //   { taskId: 'def456', status: 'success', result: 987654.32, duration: 289 },
  //   ...
  // ]
  
  await pool.terminate();
})();

V8 12.2: Compiler and Runtime Improvements

Key Enhancements

Node.js 24 bundles V8 12.2, which includes:

  • Improved JIT compilation for more predictable performance
  • Better garbage collection with reduced pause times
  • Enhanced inlining for common patterns

Performance Impact

These improvements compound across your application:

// Benchmark: Map operations
const iterations = 10_000_000;
const data = new Map();

console.time('map-writes');
for (let i = 0; i < iterations; i++) {
  data.set(`key-${i}`, Math.random());
}
console.timeEnd('map-writes');

console.time('map-reads');
for (let i = 0; i < iterations; i++) {
  data.get(`key-${i}`);
}
console.timeEnd('map-reads');

// Node.js 24: ~15% faster than Node.js 22

Migration Path and Best Practices

Step-by-Step Upgrade Guide

  1. Test locally with Node.js 24 LTS

    nvm install 24
    nvm use 24
    npm test
  2. Enable SQLite gradually (if using it)

    node --sqlite app.js
  3. Review breaking changes (minimal for 24, but check your dependencies)

    npm audit
    npm outdated
  4. Benchmark critical paths

    console.time('operation');
    // ... your code
    console.timeEnd('operation');
  5. Deploy to staging first before production

Common Pitfalls

1. Blocking the Event Loop with SQLite

Incorrect:

const db = new DatabaseSync(':memory:');
app.get('/users', (req, res) => {
  // This blocks during the query!
  const users = db.prepare('SELECT * FROM large_table').all();
  res.json(users);
});

Better:

app.get('/users', (req, res) => {
  // Offload to worker thread
  worker.postMessage({ query: 'SELECT * FROM users LIMIT 100' });
  worker.once('message', (users) => res.json(users));
});

2. Forgetting Index Management

// Slow query without index
const query1 = db.prepare('SELECT * FROM users WHERE email = ?');

// Always index columns used in WHERE clauses
db.exec('CREATE INDEX idx_email ON users(email)');

// Now it's fast
const query2 = db.prepare('SELECT * FROM users WHERE email = ?');
const user = query2.get('[email protected]'); // O(log n) instead of O(n)

3. Not Handling Worker Thread Errors

// Always listen for errors
worker.on('error', (err) => {
  console.error('Worker error:', err);
  // Re-spawn or gracefully degrade
});

worker.on('exit', (code) => {
  if (code !== 0) {
    console.error(`Worker stopped with code ${code}`);
  }
});

Testing Node.js 24 Features

Validating Your Data Structures

When working with SQLite and Worker Threads, data serialization becomes critical. Use JSON Formatter to validate your message payloads:

const message = {
  taskId: '12345',
  data: { userId: 42, action: 'login' },
  timestamp: new Date().toISOString()
};

// Serialize and validate at https://kloubot.com/tools/json
const json = JSON.stringify(message, null, 2);
console.log(json);

Benchmarking Performance

For performance-sensitive code, create benchmarks:

const { performance } = require('perf_hooks');

function benchmark(name, fn, iterations = 1000) {
  const start = performance.now();
  for (let i = 0; i < iterations; i++) {
    fn();
  }
  const end = performance.now();
  console.log(`${name}: ${((end - start) / iterations).toFixed(4)}ms per operation`);
}

const db = new DatabaseSync(':memory:');
db.exec('CREATE TABLE test (id INTEGER, value TEXT)');

const insert = db.prepare('INSERT INTO test VALUES (?, ?)');
benchmark('Insert', () => insert.run(1, 'test'), 10000);

const query = db.prepare('SELECT * FROM test WHERE id = ?');
benchmark('Query', () => query.get(1), 10000);

Why Node.js 24 Matters for Production

For startups and MVPs: Native SQLite eliminates dependency complexity while you focus on product. No database service to manage, instant backups.

For high-concurrency services: Worker Threads improvements mean you can handle more CPU-intensive work without spawning separate processes.

For edge and serverless: Smaller memory footprints and faster startup times directly reduce compute costs on platforms like AWS Lambda or Vercel.

For offline-first apps: Embedded SQLite enables rich local experiences with eventual sync to the backend.

Getting Started Today

  1. Install Node.js 24 LTS

    curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash -
    sudo apt-get install -y nodejs
  2. Create a test project

    mkdir node24-test && cd node24-test
    npm init -y
    node --sqlite index.js
  3. Experiment with the examples above and monitor performance improvements

  4. File issues or contribute to the Node.js project if you find bugs or have ideas

Resources

Node.js 24 is production-ready and available now. Start testing with your workloads today and report back on performance improvements.

This post was generated with AI assistance and reviewed for accuracy.