Skip to main content

Connecting

The LarkDatabase class is your entry point. Pass your project, database, and auth details to the constructor and start using it immediately. The connection happens automatically.

Creating an instance

The constructor takes a path string in the format projectId/databaseId, and an options object:
import { LarkDatabase } from "@lark-sh/client";

const db = new LarkDatabase("my-project/my-database", { anonymous: true });

// Start using it right away — operations queue and run once connected
db.ref("users").on("value", (snapshot) => {
  console.log(snapshot.val());
});
The connection is established lazily. You don’t need to call anything else before reading, writing, or subscribing. Operations queue automatically and execute once the connection is authenticated.

Options

All connection configuration is passed as the second argument to the constructor:
OptionTypeDefaultDescription
anonymousbooleanfalseConnect without user credentials.
tokenstringA JWT for authenticated access.
domainstring'larkdb.net'The Lark server domain.
transport'auto' | 'websocket' | 'webtransport''websocket'Which transport protocol to use.
webtransportTimeoutnumber2000Milliseconds to wait for WebTransport before falling back to WebSocket. Only applies when transport is 'auto'.
You must provide either anonymous: true or a token. If you pass both, the token takes priority.

Waiting for the connection

If you need to confirm the connection is established before proceeding, you can optionally call await db.connect():
const db = new LarkDatabase("my-project/my-database", { anonymous: true });
await db.connect(); // resolves when fully connected and authenticated
Most code doesn’t need this. Lazy queuing handles it for you. Use await db.connect() when you need to gate logic on a confirmed connection (e.g., showing a “connected” indicator, or failing fast if the server is unreachable).

Transport selection

The SDK uses WebSocket by default. To opt in to WebTransport, set transport to 'auto' or 'webtransport':
// Default — WebSocket only (you can omit the transport option entirely)
const db = new LarkDatabase("my-project/my-database", {
  anonymous: true,
});

// Try WebTransport first, fall back to WebSocket
const db = new LarkDatabase("my-project/my-database", {
  anonymous: true,
  transport: "auto",
});

// Force WebTransport only (will fail if not supported)
const db = new LarkDatabase("my-project/my-database", {
  anonymous: true,
  transport: "webtransport",
});

// Auto with a longer timeout for WebTransport negotiation
const db = new LarkDatabase("my-project/my-database", {
  anonymous: true,
  transport: "auto",
  webtransportTimeout: 5000,
});

Connection states

A connection moves through these states in order:
disconnected → connecting → connected → joined → authenticated
StateMeaning
disconnectedNo connection. Initial state or after disconnect().
connectingTransport negotiation in progress.
connectedTransport established, handshake in progress.
joinedJoined the database, awaiting authentication.
authenticatedFully ready. You can read and write data.

Properties

Once connected, several properties are available on the db instance:
// Whether the connection is fully authenticated and ready
db.connected; // boolean

// Current connection state string
db.state; // 'disconnected' | 'connecting' | 'connected' | 'joined' | 'authenticated'

// Auth info (null if anonymous)
db.auth; // { uid, provider, token } | null

// Which transport is active
db.transportType; // 'websocket' | 'webtransport' | null

// Clock skew between client and server (milliseconds)
db.serverTimeOffset; // number

// Currently registered volatile paths
db.volatilePaths; // string[]

Lifecycle events

Use callback methods to react to connection state changes:
// Fires when the connection is fully established
db.onConnect(() => {
  console.log("Connected and ready");
});

// Fires when the connection drops
db.onDisconnect(() => {
  console.log("Connection lost");
});

// Fires when the SDK is attempting to reconnect
db.onReconnecting((attempt) => {
  console.log(`Reconnection attempt #${attempt}`);
});

// Fires on connection-level errors
db.onError((error) => {
  console.error("Connection error:", error.code, error.message);
});
All lifecycle callbacks return an unsubscribe function, so you can stop listening when you no longer need them.
const unsubscribe = db.onConnect(() => {
  console.log("Connected!");
});

// Later, stop listening
unsubscribe();

Disconnecting

There are two ways to take a connection offline, and they behave differently:

disconnect()

Fully tears down the connection. Clears all cached data, removes all subscriptions, and resets the client. Use this when you’re done with the database entirely.
db.disconnect();

goOffline()

Pauses the connection but preserves your local cache and subscription registrations. When you call goOnline() later, subscriptions are re-established and you pick up where you left off.
// Pause
db.goOffline();

// Resume later
db.goOnline();
After calling disconnect(), you need to create a new LarkDatabase instance and call connect() again to re-establish the connection. After goOffline(), a simple goOnline() is enough.