Messages

Open in

The Messages interface provides methods for sending, receiving, and managing chat messages in a room. Access it via room.messages.

JavaScript

1

const messages = room.messages;

Properties

The Messages interface has the following properties:

Access to message reactions functionality for adding, removing, and subscribing to reactions on specific messages.

Subscribe to messages

messages.subscribe(listener: MessageListener): MessageSubscriptionResponse

Subscribe 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.

JavaScript

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();

Parameters

The subscribe() method takes the following parameters:

listenerrequiredMessageListener
A callback function invoked when chat message events occur.

Returns

MessageSubscriptionResponse

Returns an object with the following methods:

Unsubscribe from messages

unsubscribe(): void

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

paramsoptionalHistoryBeforeSubscribeParams
Query parameters to filter message retrieval. Messages are returned in order of most recent to oldest.
Returns

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.

Send a message

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.

JavaScript

1

2

3

4

5

const message = await messages.send({
  text: 'Hello, world!'
});

console.log('Message sent with serial:', message.serial);

Parameters

The send() method takes the following parameters:

paramsrequiredSendMessageParams
Message parameters containing the text and optional metadata/headers.

Returns

Promise<Message>

Returns a promise. The promise is fulfilled with the sent Message object, or rejected with an ErrorInfo object.

Get message history

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.

JavaScript

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();
}

Parameters

The history() method takes the following parameters:

paramsrequiredHistoryParams
Query parameters to filter and control message retrieval.

Returns

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.

Get a specific message

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.

JavaScript

1

2

const message = await messages.get('01234567890@abcdefghij');
console.log('Message text:', message.text);

Parameters

The get() method takes the following parameters:

serialrequiredString
The unique serial identifier of the message to retrieve.

Returns

Promise<Message>

Returns a promise. The promise is fulfilled with the Message object matching the given serial, or rejected with an ErrorInfo object.

Update a message

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.

JavaScript

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);

Parameters

The update() method takes the following parameters:

serialrequiredString
The unique identifier of the message to update.
updateParamsrequiredUpdateMessageParams
The new message content and properties.
detailsoptionalOperationDetails
Details to record about the update action.

Returns

Promise<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.

Delete a message

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.

JavaScript

1

2

3

4

5

6

const deletedMessage = await messages.delete(
  message.serial,
  { description: 'Removed inappropriate content' }
);

console.log('Message deleted:', deletedMessage.action);

Parameters

The delete() method takes the following parameters:

serialrequiredString
The unique identifier of the message to delete.
detailsoptionalOperationDetails
Details to record about the delete action.

Returns

Promise<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.

PaginatedResult

A PaginatedResult represents a page of results from a paginated query such as history() or historyBeforeSubscribe().

Properties

The current page of results.

Check for more pages

hasNext(): boolean

Returns true if there are more pages available by calling next().

Check if last page

isLast(): boolean

Returns true if this is the last page of results.

Get next page

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.

Get first page

first(): Promise<PaginatedResult<Message>>

Returns a promise. The promise is fulfilled with the first page of results, or rejected with an ErrorInfo object.

Get current page

current(): Promise<PaginatedResult<Message>>

Returns a promise. The promise is fulfilled with the current page of results, or rejected with an ErrorInfo object.

Example

JavaScript

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();