Message storage and history
The history feature enables users to retrieve messages that have been previously sent in a room. Ably stores chat messages for 30 days by default. You can extend this up to 365 days by contacting us.
Use the messages.get()
method to retrieve messages that have been previously sent to a room. This returns a paginated response, which can be queried further to retrieve the next set of messages.
const historicalMessages = await room.messages.get({ orderBy: OrderBy.NewestFirst, limit: 50 });
console.log(historicalMessages.items);
if (historicalMessages.hasNext()) {
const next = await historicalMessages.next();
console.log(next);
} else {
console.log('End of messages');
}
CopyCopied!
The following optional parameters can be passed when retrieving previously sent messages:
Parameter | Description |
---|---|
start | Earliest time to retrieve messages from, as a unix timestamp in milliseconds. Messages with a timestamp equal to, or greater than, this value will be returned. |
end | Latest time to retrieve messages from, as a unix timestamp in milliseconds. Messages with a timestamp less than this value will be returned. |
orderBy | The order in which to retrieve messages from; either oldestFirst or newestFirst . |
limit | Maximum number of messages to be retrieved, up to 1,000. |
Users can also retrieve historical messages that were sent to a room before the point that they registered a listener by subscribing. The order of messages returned is from most recent, to oldest. This is useful for providing conversational context when a user first joins a room, or when they subsequently rejoin it later on. It also ensures that the message history they see is continuous, without any overlap of messages being returned between their subscription and their history call.
Use the getPreviousMessages()
function returned as part of a message subscription response to only retrieve messages that were received before the listener was subscribed to the room. This returns a paginated response, which can be queried further to retrieve the next set of messages.
const { getPreviousMessages } = room.messages.subscribe(() => {
console.log('New message received');
});
const historicalMessages = await getPreviousMessages({ limit: 50 });
console.log(historicalMessages.items);
if (historicalMessages.hasNext()) {
const next = await historicalMessages.next();
console.log(next);
} else {
console.log('End of messages');
}
CopyCopied!
The following parameters can be passed when retrieving previously sent messages:
Parameter | Description |
---|---|
start | Earliest time to retrieve messages from, as a unix timestamp in milliseconds. Messages with a timestamp equal to, or greater than, this value will be returned. |
end | Latest time to retrieve messages from, as a unix timestamp in milliseconds. Messages with a timestamp less than this value will be returned. |
limit | Maximum number of messages to be retrieved, up to 1,000. |