libSQL JavaScript Client (@libsql/client)

0.5.29 · active · verified Wed Apr 22

The libSQL JavaScript Client (`@libsql/client`) is a comprehensive TypeScript/JavaScript driver for interacting with libSQL databases, a fork of SQLite. It aims for API compatibility with `better-sqlite3`, offering both synchronous and opt-in promise-based APIs. This client supports Node.js, Bun, Deno, and web browsers, facilitating connections to in-memory, local file-based, and remote libSQL instances (including Turso databases). Key differentiators include support for embedded replicas (local SQLite files that sync with remote Turso databases for offline capabilities), remote access over HTTP/WebSockets, and advanced features like encryption at rest and AI/Vector Search integration when used with Turso. The current stable version is `0.5.29`, with active development towards a `0.6.x` release, which has introduced some breaking changes and new features. The npm package `libsql` is deprecated; users should install and import from `@libsql/client` instead.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a remote libSQL (Turso) database, create a table, insert data using a batch operation, query data, and perform an update within a transaction, including a simulated rollback. It uses environment variables for secure credential management.

import { createClient } from '@libsql/client';
import 'dotenv/config';

const tursoUrl = process.env.TURSO_DATABASE_URL ?? '';
const tursoAuthToken = process.env.TURSO_AUTH_TOKEN ?? '';

if (!tursoUrl) {
  console.error('TURSO_DATABASE_URL environment variable is not set.');
  process.exit(1);
}

// Create a client for a remote Turso database
const client = createClient({
  url: tursoUrl,
  authToken: tursoAuthToken,
});

async function runExample() {
  try {
    // Create a table if it doesn't exist
    await client.execute(`
      CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        email TEXT UNIQUE NOT NULL
      );
    `);
    console.log('Table "users" ensured to exist.');

    // Insert data (batch operation for efficiency)
    const insertResult = await client.batch(
      [
        { sql: 'INSERT INTO users (name, email) VALUES (?, ?)', args: ['Alice', 'alice@example.com'] },
        { sql: 'INSERT INTO users (name, email) VALUES (?, ?)', args: ['Bob', 'bob@example.com'] }
      ],
      'write'
    );
    console.log('Inserted two users.', insertResult);

    // Query data
    const selectResult = await client.execute('SELECT * FROM users WHERE name = ?', ['Alice']);
    console.log('Query result for Alice:', selectResult.rows);

    // Update data within a transaction
    await client.transaction(async tx => {
      await tx.execute('UPDATE users SET name = ? WHERE email = ?', ['Alicia', 'alice@example.com']);
      // console.log('Updated Alice to Alicia within transaction.');
      throw new Error("Simulating a rollback for demonstration purposes"); // Transaction will roll back
    }).catch(e => {
        if (e.message !== "Simulating a rollback for demonstration purposes") {
            throw e; // Re-throw if it's not our simulated error
        }
        console.log("Transaction rolled back as intended.");
    });
    
    // Verify if update was rolled back
    const verifyResult = await client.execute('SELECT name FROM users WHERE email = ?', ['alice@example.com']);
    console.log('Name after attempted update (should be Alice):', verifyResult.rows[0].name);

  } catch (e) {
    console.error('An error occurred:', e);
  }
}

runExample();

view raw JSON →