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 24 hours by default. You can extend this up to 30 days by contacting us.

Use the messages.get() method to retrieve messages that have been previously sent to a room:

Select...
const historicalMessages = await room.messages.get({ direction: 'backwards', limit: 50 }); console.log(historicalMessages.items); if (historicalMessages.hasNext()) { const next = await historicalMessages.next(); console.log(next); } else { console.log('End of messages'); }
Copied!

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.
direction The direction in which to retrieve messages from; either forwards or backwards.
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:

Select...
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'); }
Copied!

The following parameters can be passed when retrieving previously sent messages:

Parameter Description
limit Maximum number of messages to be retrieved, up to 1,000.
Retrieve previously sent messages
v2.0