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

# Rooms

> Access room details, manage room state, and handle connection lifecycle.

A room is the virtual container. All users, presence, stores, comments, and files are scoped to a room. The Room module provides access to the current room's details.

## Room Lifecycle

Rooms are created via the [REST API](/api-reference/rooms/create-room) and cannot be created from the client SDK. The typical flow is:

1. **Your backend** creates a room via `POST /rooms`

2. **Your backend** adds a user via `POST /users`, gets a JWT token

3. **The client SDK** connects and joins the room using the JWT token

   ```typescript theme={null}
   // After your backend creates a room and user:
   const client = new CollabKitClient({
     serverUrl: 'https://api.collab-kit.com',
     authToken: jwtFromBackend,
   });
   await client.join(); // defaults to { role: 'editor' }
   // currentUser.status is now 'online'
   // Other users receive a 'userJoined' event only when this session is an editor
   ```

4. **The room** tracks participants, presence, and all collaboration state

   Users can join as an editor or viewer:

   ```typescript theme={null}
   await client.join({ role: 'viewer' });
   console.log(client.role); // 'viewer'

   await client.updateRole('editor');
   ```

   Roles are session-scoped. Editors are active collaborators and appear in `client.users.active`; viewers receive realtime updates and can follow users, but cannot write collaboration state.

   After connecting and joining, [room information](/types/core#collabkitroom) is available using:

   ```typescript theme={null}
   console.log(client.currentRoom);
   // { id, name, state, active_participants, duration_seconds, ... }
   ```

   You can also fetch the current room's details from the server:

   <Note>
     This method returns room details. Use `client.users.list(...)` for paginated users and `client.users.active` for active editors.
   </Note>

   ```typescript theme={null}
   const room = await client.room.get();
   console.log(room);

   // Optionally pass a room ID to fetch a different room:
   const otherRoom = await client.room.get({ roomId: 'other-room-id' });
   ```

## Connection Lifecycle

The client exposes low-level connection events via `client.socket`. Use these to monitor connection state, handle disconnections, and implement custom reconnection logic like so:

```typescript theme={null}
client.socket.on('connected', () => {
  console.log('Initial WebSocket connection established');
});
```

### Lifecycle Events

| Event          | Payload               | Description                                                              |
| -------------- | --------------------- | ------------------------------------------------------------------------ |
| `connected`    | none                  | Initial WebSocket connection opened (authentication happens at `join()`) |
| `disconnected` | none                  | WebSocket connection closed                                              |
| `reconnecting` | `{ attempt: number }` | A reconnection attempt is starting                                       |
| `reconnected`  | none                  | Successfully reconnected and state has been rehydrated                   |
| `failed`       | none                  | All reconnection attempts have been exhausted                            |
| `authFailed`   | none                  | The JWT token was rejected by the server                                 |

### Auto-Reconnection

The SDK automatically reconnects when the WebSocket connection drops unexpectedly. It uses **exponential backoff** with configurable parameters:

* Reconnection starts immediately after disconnection
* Each subsequent attempt waits longer (exponential backoff)
* After all attempts are exhausted, the `failed` event fires

### Pre-Reconnect Hooks (Optional)

Register a handler that runs before each reconnection attempt. Use this to refresh tokens or perform setup before reconnecting:

```typescript theme={null}
client.socket.onReconnect(async () => {
  // Refresh the JWT token before reconnecting
  const newToken = await fetchNewToken();
  client.authToken = newToken;
});
```

### Connection States

The connection transitions through these states:

```
disconnected -> connecting -> connected -> disconnected
                                  |
                                  v
                            reconnecting -> reconnected
                                  |
                                  v
                               failed
```

## Examples

### Offline Queue

Buffer actions while offline and replay them on reconnect:

```typescript theme={null}
const offlineQueue: (() => Promise<void>)[] = [];
let isOnline = true;

client.socket.on('disconnected', () => {
  isOnline = false;
});

client.socket.on('reconnected', async () => {
  isOnline = true;
  // Replay queued actions
  while (offlineQueue.length > 0) {
    const action = offlineQueue.shift();
    await action?.();
  }
});

// Wrapper for store operations
async function safeStoreSet(key: string, value: any) {
  const action = () => client.stores.tasks.set({ key, value });

  if (isOnline) {
    await action();
  } else {
    offlineQueue.push(action);
  }
}
```
