---
source_url: https://www.pubnub.com/docs/general/basics/retrieve-old-messages
title: Retrieve old messages
updated_at: 2026-05-20T11:05:06.343Z
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Retrieve old messages

Real-time in‑app messaging delivers data quickly. Sometimes you need messages sent earlier.

PubNub lets you [retain and retrieve historical messages](https://www.pubnub.com/docs/general/storage). You need the channel name and the message’s timetoken. A timetoken is a 17‑digit timestamp created when PubNub publishes a message. Enable Message Persistence in the [Admin Portal](https://admin.pubnub.com). Then set [how long PubNub stores messages](https://www.pubnub.com/docs/general/storage#message-retention). PubNub manages retention with storage periods based on your plan.

You can retrieve historical messages from one or multiple channels. You can also [control the time range](https://www.pubnub.com/docs/general/storage#retrieve-messages) and choose the return order. A request returns up to 100 messages for one channel. For multiple channels, it returns up to 25 per channel, with a maximum of 500 total. If you only need counts, [retrieve the number of messages you missed](https://www.pubnub.com/docs/general/storage#get-message-counts).

Most use cases retrieve messages missed since the client was last online. Provide the `end` parameter with the timetoken of the last received message. The following code returns the last 100 messages on the `chats_guilds.mages_guild` channel.

:::note User ID / UUID
User ID is also referred to as **UUID/uuid** in some APIs and server responses but **holds the value** of the **userId** parameter you [set during initialization](https://www.pubnub.com/docs/general/setup/users-and-devices#set-the-user-id).
:::

###### JavaScript

```javascript
pubnub.fetchMessages(
  {
    channels: ["chats_guilds.mages_guild"],
    end: '15343325004275466',
    count: 100
  },
  function(status, response) {
    console.log(status, response);
  }
);
```

###### Swift

```swift
pubnub.fetchMessageHistory(
  for: ["chats_guilds.mages_guild"],
  end: "15343325004275466"
) { result in
  switch result {
    case let .success(response):
      print("Successful History Fetch Response: \(response)")

    case let .failure(error):
      print("Failed History Fetch Response: \(error.localizedDescription)")
  }
}
```

###### Objective-C

```objectivec
self.pubnub.history()
  .channels(@[@"chats_guilds.mages_guild"])
  .end(15343325004275466).limit(100)
  .performWithCompletion(^(PNHistoryResult *result, PNErrorStatus *status) {
    // handle returned messages in result
});
```

###### Java

```java
pubNub.fetchMessages()
    .channels(Arrays.asList("chats_guilds.mages_guild"))
    .async(result -> {
        result.onSuccess(res -> {
            final Map<String, List<PNFetchMessageItem>> channelToMessageItemsMap = res.getChannels();
            final Set<String> channels = channelToMessageItemsMap.keySet();
            for (final String channel : channels) {
                List<PNFetchMessageItem> pnFetchMessageItems = channelToMessageItemsMap.get(channel);
                for (final PNFetchMessageItem fetchMessageItem : pnFetchMessageItems) {
                    System.out.println(fetchMessageItem.getMessage());
                    System.out.println(fetchMessageItem.getMeta());
                    System.out.println(fetchMessageItem.getTimetoken());
                }
            }
        }).onFailure(exception -> {
            exception.printStackTrace();
        });
    });
```

###### C#

```csharp
pubnub.FetchHistory()
  .Channels(new string[] { "chats_guilds.mages_guild" })
  .MaximumPerChannel(100)
  .End(15343325004275466)
  .Execute(new PNFetchHistoryResultExt((result, status) => {
    // handle returned messages in result
  }));
```

###### Python

```python
envelope = pubnub.fetch_messages()\
  .channels(["chats_guilds.mages_guild"])\
  .count(100)\
  .end(15343325004275466)\
  .sync()
```

###### Dart

```dart
var result = await pubnub.batch.fetchMessages({'chats_guilds.mages_guild'}, count: 100);
```

###### Kotlin

```kotlin
pubnub.fetchMessages(
    channels = listOf("chats_guilds.mages_guilds"),
    page = PNBoundedPage(limit = 100)
).async { result, status ->
    if (!status.error) {
        result!!.channels.forEach { (channel, messages) ->
            println("Channel: $channel")
            messages.forEach { messageItem: PNFetchMessageItem ->
                println(messageItem.message) // actual message payload
                println(messageItem.timetoken) // included by default
                messageItem.actions?.forEach { actionType, map ->
                    println("Action type: $actionType")
                    map.forEach { (actionValue, publishers) ->
                        println("Action value: $actionValue")
                        publishers.forEach { publisher ->
                            println("UUID: ${publisher.uuid}")
                            println("Timetoken: ${publisher.actionTimetoken}")
                        }
                    }
                }
            }
        }
    } else {
        // handle error
        status.exception?.printStackTrace()
    }
}
```

If messages include any [emojis, actions, or delivery acknowledgments](https://www.pubnub.com/docs/general/messages/actions), you can [retrieve them](https://www.pubnub.com/docs/general/messages/actions#retrieve-actions). By default, history doesn’t include the custom message type. You can enable it.

Having read how to work with historical messages, let's focus back on the present. As your channels get more traction and users start to subscribe, it's worthwhile to [understand how to check who's currently online](https://www.pubnub.com/docs/general/basics/check-user-presence).

## Terms in this document

* **Channel** - A pathway for sending and receiving messages between devices, created automatically when you first use it, that can handle any number of users and messages for different communication needs, like 1-1 text chats, group conversations, and other data streaming.
* **Channel pattern** - A way to group and analyze channel data to track performance metrics like message counts and user engagement over time with PubNub Insights.
* **Timetoken** - A unique identifier for each message that represents the number of 100-nanosecond intervals since January 1, 1970, for example, 16200000000000000.
