> ## Documentation Index
> Fetch the complete documentation index at: https://docs.larksh.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Connecting

> Manage connections, lifecycle, and transport options

# 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:

```typescript theme={null}
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:

| Option                | Type                                      | Default        | Description                                                                                                        |
| --------------------- | ----------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------ |
| `anonymous`           | `boolean`                                 | `false`        | Connect without user credentials.                                                                                  |
| `token`               | `string`                                  | —              | A JWT for authenticated access.                                                                                    |
| `domain`              | `string`                                  | `'larkdb.net'` | The Lark server domain.                                                                                            |
| `transport`           | `'auto' \| 'websocket' \| 'webtransport'` | `'websocket'`  | Which transport protocol to use.                                                                                   |
| `webtransportTimeout` | `number`                                  | `2000`         | Milliseconds to wait for WebTransport before falling back to WebSocket. Only applies when `transport` is `'auto'`. |

<Note>
  You must provide either `anonymous: true` or a `token`. If you pass both, the token takes priority.
</Note>

## Waiting for the connection

If you need to confirm the connection is established before proceeding, you can optionally call `await db.connect()`:

```typescript theme={null}
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'`:

```typescript theme={null}
// 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
```

| State           | Meaning                                               |
| --------------- | ----------------------------------------------------- |
| `disconnected`  | No connection. Initial state or after `disconnect()`. |
| `connecting`    | Transport negotiation in progress.                    |
| `connected`     | Transport established, handshake in progress.         |
| `joined`        | Joined the database, awaiting authentication.         |
| `authenticated` | Fully ready. You can read and write data.             |

## Properties

Once connected, several properties are available on the `db` instance:

```typescript theme={null}
// 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:

```typescript theme={null}
// 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);
});
```

<Tip>
  All lifecycle callbacks return an unsubscribe function, so you can stop listening when you no longer need them.
</Tip>

```typescript theme={null}
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.

```typescript theme={null}
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.

```typescript theme={null}
// Pause
db.goOffline();

// Resume later
db.goOnline();
```

<Warning>
  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.
</Warning>
