> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/ably/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Message history

The history feature enables users to retrieve messages that have been previously sent in a room. [Message persistence](/docs/chat/rooms#persistence) is enabled by default for all chat rooms, with messages stored for 30 days. You can extend this retention period up to 365 days by [contacting us](https://ably.com/support).

<Note>
  Every message is redundantly stored across [multiple isolated datacenters](/docs/platform/architecture/fault-tolerance#the-core-layer-stateful-resilience) before acknowledgment, ensuring your chat history is always available when you need it.
</Note>

## Retrieve previously sent messages

Use the [`messages.history()`](/docs/chat/api/javascript/messages#history) 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.

```javascript theme={null}
const historicalMessages = await room.messages.history({ 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');
}
```

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

| Parameter | Description                                                                                                                                                     | Default                    |
| --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
| 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. | Earliest available message |
| end       | Latest time to retrieve messages from, as a unix timestamp in milliseconds. Messages with a timestamp less than this value will be returned.                    | Current time               |
| orderBy   | The order in which to retrieve messages from; either `oldestFirst` or `newestFirst`.                                                                            | `newestFirst`              |
| limit     | Maximum number of messages to be retrieved per page, up to 1,000.                                                                                               | 100                        |

### Understanding message ordering

The `orderBy` parameter determines the messages retrieved and their return order:

| Order                   | Retrieves                       | Returns                 | Use case                       |
| ----------------------- | ------------------------------- | ----------------------- | ------------------------------ |
| `newestFirst` (default) | Most recent messages            | `[newest, ..., oldest]` | Standard chat application      |
| `oldestFirst`           | Oldest messages from room start | `[oldest, ..., newest]` | Archives, exports, admin tools |

For the majority of chat UIs, the default behavior of `newestFirst` will be correct. This retrieves messages from most recent to oldest, which you can then reverse to display the newest message at the bottom of the UI.

## Retrieve messages sent prior to subscribing

Retrieve historical messages sent before subscribing using `historyBeforeSubscribe()`. Messages are returned in order, from the most recent to the oldest (newestFirst). This is useful for providing conversational context when a user joins or rejoins a room, ensuring continuous message history without overlap.

Use the [`historyBeforeSubscribe()`](/docs/chat/api/javascript/messages#historyBeforeSubscribe) function returned as part of a [message subscription](/docs/chat/rooms/messages#subscribe) 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.

```javascript theme={null}
const { historyBeforeSubscribe } = room.messages.subscribe(() => {
  console.log('New message received');
});

const historicalMessages = await historyBeforeSubscribe({ limit: 50 });
console.log(historicalMessages.items);
if (historicalMessages.hasNext()) {
  const next = await historicalMessages.next();
  console.log(next);
} else {
  console.log('End of messages');
}
```

The following optional parameters can be passed when retrieving messages before subscribing:

| Parameter | Description                                                                                                                                                     | Default                    |
| --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
| 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. | Earliest available message |
| end       | Latest time to retrieve messages from, as a unix timestamp in milliseconds. Messages with a timestamp less than this value will be returned.                    | Current time               |
| limit     | Maximum number of messages to be retrieved per page, up to 1,000.                                                                                               | 100                        |
