The ChatClient class is the main entry point for using the Ably Chat SDK. It provides access to chat rooms, connection management, and the underlying Ably Realtime client.
The Chat SDK is built on top of the Ably Pub/Sub SDK and uses that to establish a connection with Ably. Instantiate a realtime client using the Pub/Sub SDK and pass the generated client into the Chat constructor.
1
2
3
4
import { LogLevel } from '@ably/chat'
const realtimeClient = new Ably.Realtime({ key: 'demokey:*****', clientId: '<clientId>'});
const chatClient = new ChatClient(realtimeClient, { logLevel: LogLevel.Error });An API key is required to authenticate with Ably. API keys are used either to authenticate directly with Ably using basic authentication, or to generate tokens for untrusted clients using JWT authentication.
Properties
The ChatClient interface has the following properties:
roomsRoomsconnectionConnectionclientIdString or Undefinedundefined until authenticated with a token.realtimeAbly.RealtimeclientOptionsChatClientOptionsCreate a new chat client
new ChatClient(realtime: Realtime, clientOptions?: ChatClientOptions)Create a new ChatClient instance by passing an Ably Realtime client and optional configuration options.
1
2
3
4
5
6
7
8
9
import * as Ably from 'ably';
import { ChatClient } from '@ably/chat';
const realtimeClient = new Ably.Realtime({
key: 'demokey:*****',
clientId: 'user-123'
});
const chatClient = new ChatClient(realtimeClient, clientOptions);Parameters
The ChatClient() constructor takes the following parameters:
realtimerequiredAbly.RealtimeclientId. The clientId is required for all chat operations.clientOptionsoptionalChatClientOptionsDispose of the chat client
chatClient.dispose(): Promise<void>Disposes of the ChatClient instance and releases all resources, including all chat rooms. After calling this method, the ChatClient instance is no longer usable.
1
await chatClient.dispose();Returns
Promise<void>
Returns a promise. The promise is fulfilled when the client has been disposed, or rejected with an ErrorInfo object.
ErrorInfo
A standardized, generic Ably error object that contains an Ably-specific status code, and a generic HTTP status code. All errors returned from Ably are compatible with the ErrorInfo structure.
codeNumberstatusCodeNumbermessageStringcauseString, ErrorInfo, or ErrorExample
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import * as Ably from 'ably';
import { ChatClient, LogLevel } from '@ably/chat';
const realtimeClient = new Ably.Realtime({
key: 'demokey:*****',
clientId: 'user-123'
});
const chatClient = new ChatClient(realtimeClient, {
logLevel: LogLevel.Debug
});
// Access rooms
const room = await chatClient.rooms.get('my-room');
// Check connection status
console.log(chatClient.connection.status);
// Get current user ID
console.log(chatClient.clientId);