Messages

You can send and receive messages in a chat room with any number of participants. These users subscribe to messages by registering a listener, and send messages to all users that are subscribed to receive them.

Subscribe to receive messages in a room by registering a listener. Use the messages.subscribe() method in a room to receive all messages that are sent to it:

Select...
const {unsubscribe} = room.messages.subscribe(message) => { console.log(message); }
Copied!

The following is the structure of a message:

{ "timeserial": "e91RB0GOQBcvyJ53053074@1718191654749-0", "clientId": "basketLover014", "roomId": "basketball-stream", "text": "What a shot!", "headers": {}, "metadata": {}, "createdAt": "2024-06-12T11:37:59.988Z", }
Copied!

The following are the properties of a message:

Property Description Type
timeserial An Ably-generated ID used to determine the order the message was sent in. String
clientId The client identifier of the user that sent the message. String
roomId The name of the room the message was sent to. String
text The message contents. String
headers Optional headers for adding additional information to a message, such as the relative timestamp of a livestream video, or flagging a message as important. Do not use the headers for authoritative information. There is no server-side validation. When reading headers treat them like user input. Object
metadata Optional additional metadata about the message, such as animations, effects or links to other resources such as images. This information is not read by Ably. Do not use metadata for authoritative information. There is no server-side validation. When reading metadata treat it like user input. Object
createdAt The time the message was sent. Date

Unsubscribe from messages to remove previously registered listeners.

Use the unsubscribe() function returned in the subscribe() response to remove a listener:

Select...
// Initial subscription const { unsubscribe } = room.messages.subscribe((message) => console.log(message)); // To remove the listener unsubscribe();
Copied!

Use the messages.unsubscribeAll() method to deregister all chat message listeners in a room:

Select...
await room.messages.unsubscribeAll();
Copied!

Use the messages.send() method to send a message in a chat room. All users that are subscribed to messages on that room will receive it:

Select...
await room.messages.send('hello');
Copied!
Subscribe to messages
v2.0