Chat JavaScript SDK: Messages
The Messages interface provides methods for sending, receiving, and managing chat messages in a room. Access it via room.messages.
1
const messages = room.messages;The Messages interface has the following properties:
reactionsMessageReactionsmessages.subscribe(listener: MessageListener): MessageSubscriptionResponseSubscribe to chat message events in the room. This method allows you to listen for new messages and provides access to historical messages that occurred before the subscription was established.
The room must be attached for the listener to receive new message events.
1
2
3
4
5
6
7
8
9
const { unsubscribe, historyBeforeSubscribe } = messages.subscribe((event) => {
console.log('Received message:', event.message.text);
});
// Get messages sent before subscribing
const history = await historyBeforeSubscribe();
// To stop receiving messages
unsubscribe();The subscribe() method takes the following parameters:
listenerrequiredMessageListenerMessageSubscriptionResponse
Returns an object with the following methods:
Unsubscribe from messages
unsubscribe(): voidCall unsubscribe() to stop listening for message events.
Get messages from before the subscription started
historyBeforeSubscribe(params?: HistoryBeforeSubscribeParams): Promise<PaginatedResult<Message>>Get messages sent to the room from before the subscription was established.
Parameters
The historyBeforeSubscribe() method takes the following parameters:
paramsoptionalHistoryBeforeSubscribeParamsReturns
Promise<PaginatedResult<Message>>
Returns a promise. The promise is fulfilled with a PaginatedResult containing an array of Message objects, or rejected with an ErrorInfo object.
messages.send(params: SendMessageParams): Promise<Message>Send a message to the chat room. The message will be delivered to all subscribers in real-time.
This method uses the Ably Chat REST API and does not require the room to be attached.
1
2
3
4
5
const message = await messages.send({
text: 'Hello, world!'
});
console.log('Message sent with serial:', message.serial);The send() method takes the following parameters:
paramsrequiredSendMessageParamsPromise<Message>
Returns a promise. The promise is fulfilled with the sent Message object, or rejected with an ErrorInfo object.
messages.history(params: HistoryParams): Promise<PaginatedResult<Message>>Get messages that have been previously sent to the chat room. This method retrieves historical messages based on the provided query options, allowing you to paginate through message history, filter by time ranges, and control the order of results.
This method uses the Ably Chat REST API and does not require the room to be attached.
1
2
3
4
5
6
7
8
9
10
11
const history = await messages.history({
limit: 50,
orderBy: OrderBy.NewestFirst
});
console.log('Messages:', history.items);
// Get next page if available
if (history.hasNext()) {
const nextPage = await history.next();
}The history() method takes the following parameters:
paramsrequiredHistoryParamsPromise<PaginatedResult<Message>>
Returns a promise. The promise is fulfilled with a PaginatedResult containing an array of Message objects, or rejected with an ErrorInfo object.
messages.get(serial: string): Promise<Message>Get a specific message by its unique serial identifier.
This method uses the Ably Chat REST API and does not require the room to be attached.
1
2
const message = await messages.get('01234567890@abcdefghij');
console.log('Message text:', message.text);The get() method takes the following parameters:
serialrequiredStringPromise<Message>
Returns a promise. The promise is fulfilled with the Message object matching the given serial, or rejected with an ErrorInfo object.
messages.update(serial: string, updateParams: UpdateMessageParams, details?: OperationDetails): Promise<Message>Update a message in the chat room. This method modifies an existing message's content, metadata, or headers. The update creates a new version of the message while preserving the original serial identifier. Subscribers will receive an update event in real-time.
This method uses the Ably Chat REST API and does not require the room to be attached.
1
2
3
4
5
6
7
const updatedMessage = await messages.update(
message.serial,
{ text: 'Updated message text' },
{ description: 'Fixed typo' }
);
console.log('Message updated:', updatedMessage.version);The update() method takes the following parameters:
serialrequiredStringupdateParamsrequiredUpdateMessageParamsdetailsoptionalOperationDetailsPromise<Message>
Returns a promise. The promise is fulfilled with the updated Message object, or rejected with an ErrorInfo object. The returned message will have its action property set to updated.
messages.delete(serial: string, details?: OperationDetails): Promise<Message>Delete a message in the chat room. This method performs a "soft delete" on a message, marking it as deleted rather than permanently removing it. The deleted message will still be visible in message history but will be flagged as deleted. Subscribers will receive a deletion event in real-time.
This method uses the Ably Chat REST API and does not require the room to be attached.
1
2
3
4
5
6
const deletedMessage = await messages.delete(
message.serial,
{ description: 'Removed inappropriate content' }
);
console.log('Message deleted:', deletedMessage.action);The delete() method takes the following parameters:
serialrequiredStringdetailsoptionalOperationDetailsPromise<Message>
Returns a promise. The promise is fulfilled with the deleted Message object, or rejected with an ErrorInfo object. The returned message will have its action property set to deleted.
A PaginatedResult represents a page of results from a paginated query such as history() or historyBeforeSubscribe().
itemsMessage[]hasNext(): booleanReturns true if there are more pages available by calling next().
isLast(): booleanReturns true if this is the last page of results.
next(): Promise<PaginatedResult<Message> | null>Returns a promise. The promise is fulfilled with the next page of results, or null if there are no more pages, or rejected with an ErrorInfo object.
first(): Promise<PaginatedResult<Message>>Returns a promise. The promise is fulfilled with the first page of results, or rejected with an ErrorInfo object.
current(): Promise<PaginatedResult<Message>>Returns a promise. The promise is fulfilled with the current page of results, or rejected with an ErrorInfo object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { ChatMessageEventType, OrderBy } from '@ably/chat';
const room = await chatClient.rooms.get('my-room');
await room.attach();
// Subscribe to messages
const { unsubscribe, historyBeforeSubscribe } = room.messages.subscribe((event) => {
const msg = event.message;
switch (event.type) {
case ChatMessageEventType.Created:
console.log(`${msg.clientId}: ${msg.text}`);
break;
case ChatMessageEventType.Updated:
console.log(`Message updated: ${msg.text}`);
break;
case ChatMessageEventType.Deleted:
console.log(`Message deleted: ${msg.serial}`);
break;
}
});
// Get recent history
const history = await room.messages.history({ limit: 10 });
history.items.forEach(msg => {
console.log(`[History] ${msg.clientId}: ${msg.text}`);
});
// Send a message
const sent = await room.messages.send({ text: 'Hello everyone!' });
// Update the message
await room.messages.update(sent.serial, { text: 'Hello everyone! (edited)' });
// Clean up
unsubscribe();