---
source_url: https://www.pubnub.com/docs/sdks/javascript/api-reference/storage-and-playback
title: Message Persistence API for JavaScript SDK
updated_at: 2026-05-25T11:28:08.771Z
sdk_name: PubNub JavaScript SDK
sdk_version: 11.0.1
---

> 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


# Message Persistence API for JavaScript SDK

PubNub JavaScript SDK, use the latest version: 11.0.1

Install:

```bash
npm install pubnub@11.0.1
```

Message Persistence gives you real-time access to the history of messages published to PubNub. Each message is timestamped to the nearest 10 nanoseconds and stored across multiple availability zones in several geographic locations. You can encrypt stored messages with AES-256 so they are not readable on PubNub’s network. For details, see [Message Persistence](https://www.pubnub.com/docs/general/storage).

You control how long messages are stored through your account’s retention policy. Options include: 1 day, 7 days, 30 days, 3 months, 6 months, 1 year, or Unlimited.

You can retrieve the following:

* Messages
* Message reactions
* Files (using the File Sharing API)

:::note Supported and recommended asynchronous patterns
PubNub supports [Callbacks, Promises, and Async/Await](https://javascript.info/async) for asynchronous JS operations. The recommended pattern is Async/Await and all sample requests in this document are based on it. This pattern returns a status only on detecting an error. To receive the status errors, you must use the [try...catch](https://javascript.info/try-catch) syntax in your code.
:::

## Fetch history

:::warning Requires Message Persistence
Enable Message Persistence for your key in the [Admin Portal](https://admin.pubnub.com/). See how to [enable add-on features](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-).
:::

Fetch historical messages from one or more channels. Use `includeMessageActions` to include message actions.

You can control how messages are returned and in what order.

* If you specify only the `start` parameter (without `end`), you receive messages older than the `start` timetoken.
* If you specify only the `end` parameter (without `start`), you receive messages from that `end` timetoken and newer.
* If you specify both `start` and `end`, you retrieve messages between those timetokens (inclusive of the `end` value).

You can receive up to 100 messages for a single channel. For multiple channels (up to 500), you can receive up to 25 messages per channel. If more messages match the time range, make iterative calls and adjust the `start` timetoken to page through the results.

### Method(s)

Use the following method(s) in the JavaScript SDK:

```javascript
pubnub.fetchMessages({
    channels: Array<string>,
    count: number,
    includeMessageType: boolean,
    includeCustomMessageType: boolean,
    includeUUID: boolean,
    includeMeta: boolean,
    includeMessageActions: boolean,
    start: string,
    end: string
})
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channels | Array<string> | Yes |  | Channels to fetch history messages from (up to 500). |
| count | number | Optional | `100 or 25` | Number of historical messages to return per channel. Default is `100` (single) and `25` (multi) or `25` with `includeMessageActions`. |
| includeMessageType | boolean | Optional | `true` | Whether to pass `true` to include message type. Default is `true`. |
| includeCustomMessageType | Boolean | Optional |  | Whether to retrieve messages with the custom message type. For more information, refer to [Retrieving Messages](https://www.pubnub.com/docs/general/storage#retrieve-messages). |
| includeUUID | boolean | Optional | `true` | Whether to receive the publisher `uuid`. Default is `true`. |
| includeMeta | boolean | Optional |  | Whether to include the meta object (if provided at publish time) in the response. |
| includeMessageActions | boolean | Optional |  | Whether to retrieve history messages with message actions. If used, limit is 25 per single channel and only one `channel` is allowed. The response may be truncated; a `more` link is provided. |
| start | string | Optional |  | Timetoken delimiting the start (exclusive) of the time slice. |
| end | string | Optional |  | Timetoken delimiting the end (inclusive) of the time slice. |

:::note Truncated response
If you fetch messages with message actions, the response may be truncated when internal limits are reached. If truncated, a `more` property is returned with additional parameters. Make iterative calls to history, adjusting the parameters to fetch more messages.
:::

### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

Retrieve a message from a channel:

###### JavaScript

```javascript
import PubNub from 'pubnub';
// Initialize PubNub with your keys
const pubnub = new PubNub({
  publishKey: 'YOUR_PUBLISH_KEY',
  subscribeKey: 'YOUR_SUBSCRIBE_KEY',
  userId: 'YOUR_USER_ID',
});
```

```javascript
// Function to fetch message history
try {
  const result = await pubnub.fetchMessages({
    channels: ['my-channel'],
    count: 1, // Number of messages to retrieve
    includeCustomMessageType: true, // if you want to include custom message type in the response
    start: 'replace-with-start-timetoken', // start timetoken
    end: 'replace-with-end-timetoken', // end timetoken
  });
  console.log('Fetched Messages:', result);
} catch (error) {
  console.error(
    `Messages fetch failed: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
```

###### React

In React, call `fetchMessages` inside a `useEffect` hook on component mount and store the results in state to display them in your UI.

```jsx
import React, { useState, useEffect } from 'react';
import PubNub from 'pubnub';

const pubnub = new PubNub({
  publishKey: 'YOUR_PUBLISH_KEY',
  subscribeKey: 'YOUR_SUBSCRIBE_KEY',
  userId: 'YOUR_USER_ID',
});

function MessageHistory() {
  const [messages, setMessages] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    async function loadHistory() {
      try {
        const result = await pubnub.fetchMessages({
          channels: ['my_channel'],
          count: 25,
        });
        const channelMessages = result.channels['my_channel'] ?? [];
        setMessages(channelMessages.map((m) => m.message));
      } catch (error) {
        console.error('fetchMessages failed:', error);
      } finally {
        setIsLoading(false);
      }
    }
    loadHistory();
  }, []);

  if (isLoading) return <p>Loading history...</p>;

  return (
    <ul>
      {messages.map((msg, i) => (
        <li key={i}>{typeof msg === 'object' ? JSON.stringify(msg) : msg}</li>
      ))}
    </ul>
  );
}
```

### Response

```javascript
//Example of status
{
    error: false,
    operation: 'PNFetchMessagesOperation',
    statusCode: 200
}

//Example of response
{
    "channels":{
        "my-channel":[
            {
                "message":"message_1",
                "timetoken":"15483367794816642",
                "uuid":"my-uuid",
                "message_type":null,
                // the value depends on the custom message type
                // that the message was sent with
                "custom_message_type":"text-message"
            }
        ]
    }
}
```

### Other examples

#### Fetch messages with metadata and actions

```javascript
try {
  const response = await pubnub.fetchMessages({
    channels: ['my_channel'],
    stringifiedTimeToken: true,
    includeMeta: true,
    includeMessageActions: true,
    includeCustomMessageType: true,
  });
  console.log('fetch messages response:', response);
} catch (error) {
  console.error(
    `fetch messages failed with error: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
```

#### Fetch messages with metadata and actions response

:::note Return information on message actions
To get information on actions taken on specific messages within a PubNub channel (like reactions, edits, deletions, or other custom-defined actions) use the `actions` object instead of the deprecated `data` object.
:::

```javascript
// Example of status
{
    "error": false,
    "operation": "PNFetchMessagesOperation",
    "statusCode": 200
}

// Example of response
{
    "channels":{
        "my_channel":[
            {
                "channel : "my_channel",
                "timetoken":"15741125155552287",
                "message":{
                    "text":"Hello world!",
                },
                "messageType": 1,
                "customMessageType": "your custom type",
                "uuid": "someUserId",
                "meta":""
                "actions":{
                    "reaction":{
                        "smiley_face":[
                            {
                                "uuid":"my-uuid",
                                "actionTimetoken":"15741125155943280"
                            }
                        ]
                    }
                }
            }
        ]
    },
"more": {
    "url": "/v3/history-with-actions/sub-key/subscribeKey/channel/myChannel?start=15610547826970000&max=98",
    "start": "15610547826970000",
    "max": 98
}
}
```

## Delete messages from history

:::warning Requires Message Persistence
Enable Message Persistence for your key in the [Admin Portal](https://admin.pubnub.com/). See how to [enable add-on features](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-).
:::

Remove messages from the history of a specific channel.

:::note Required setting
Enable `Delete-From-History` for your key in the Admin Portal and initialize the SDK with a secret key.
:::

### Method(s)

To `Delete Messages from History`, you can use the following method(s) in the JavaScript SDK.

```javascript
pubnub.deleteMessages({
    channel: string,
    start: string,
    end: string
})
```

:::note Method behavior
The Delete Messages method behaves slightly differently than other history methods. Note that the `start` parameter is exclusive and the `end` parameter is inclusive.
:::

| Parameter | Description |
| --- | --- |
| `channel` *Type: string | Specifies `channel` messages to be deleted from history. |
| `start`Type: string | Timetoken delimiting the `start` of time slice (exclusive) to delete messages from. |
| `end`Type: string | Timetoken delimiting the `end` of time slice (inclusive) to delete messages from. |

### Sample code

```javascript
try {
  const result = await pubnub.deleteMessages({
    channel: 'ch1',
    start: 'replace-with-start-timetoken',
    end: 'replace-with-end-timetoken',
  });
  console.log('Messages deleted successfully:', result);
} catch (error) {
  console.error(
    `Messages delete failed: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
```

### Response

```javascript
{
    error: false,
    operation: 'PNDeleteMessagesOperation',
    statusCode: 200
}
```

### Other examples

#### Delete specific message from a Message Persistence

To delete a specific message, pass the `publish timetoken` (received from a successful publish) in the `End` parameter and `timetoken +/- 1` in the `Start` parameter. For example, if `15526611838554310` is the `publish timetoken`, pass `15526611838554309` in `Start` and `15526611838554310` in `End` parameters respectively as shown in the following code snippet.

```javascript
try {
  const response = await pubnub.deleteMessages({
    channel: 'ch1',
    start: 'replace-with-start-timetoken',
    end: 'replace-with-end-timetoken',
  });
  console.log('delete messages response:', response);
} catch (error) {
  console.error(
    `delete messages failed with error: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
```

## Message counts

:::warning Requires Message Persistence
Enable Message Persistence for your key in the [Admin Portal](https://admin.pubnub.com/). See how to [enable add-on features](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-).
:::

Return the number of messages published since the given time. The count is the number of messages with a timetoken greater than or equal to `channelTimetokens`.

:::note Unlimited message retention
Only messages from the last 30 days are counted.
:::

### Method(s)

You can use the following method(s) in the JavaScript SDK:

```javascript
pubnub.messageCounts({
    channels: Array<string>,
    channelTimetokens: Array<string>
})
```

| Parameter | Description |
| --- | --- |
| `channels` *Type: Array`<string>`Default: n/a | Channels to fetch the message count. |
| `channelTimetokens` *Type: Array`<string>`Default: n/a | Array in the same order as channels; a single timetoken applies to all channels; otherwise, lengths must match or the function returns a `PNStatus` error. |

### Sample code

```javascript
try {
  const result = await pubnub.messageCounts({
    channels: ['chats.room1', 'chats.room2'],
    channelTimetokens: ['replace-with-channel-timetoken-(optional)'],
  });
  console.log('Message counts retrieved successfully:', result);
} catch (error) {
  console.error(
    `Message counts retrieval failed: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
```

### Returns

:::note Message count
`Channels` without messages have a count of 0. `Channels` with 10,000 messages or more have a count of 10000.
:::

```javascript
{
    channels: {
        ch1: 49
    }
}
```

### Status response

```javascript
{
    error: false,
    operation: 'PNMessageCountsOperation',
    statusCode: 200
}
```

### Other examples

#### Retrieve count of messages using different timetokens for each channel

```javascript
try {
  const response = await pubnub.messageCounts({
    channels: ['ch1', 'ch2', 'ch3'],
    channelTimetokens: [
      'replace-with-channel-timetoken-ch1', // timetoken for channel ch1
      'replace-with-channel-timetoken-ch2', // timetoken for channel ch2
      'replace-with-channel-timetoken-ch3', // timetoken for channel ch3
    ],
  });
  console.log('message count response:', response);
} catch (error) {
  console.error(
    `message count failed with error: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
```

## History (deprecated)

:::warning Requires Message Persistence
Enable Message Persistence for your key in the [Admin Portal](https://admin.pubnub.com/). See how to [enable add-on features](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-).
:::

:::note Alternative method
This method is deprecated. Use [fetch history](#fetch-history) instead.
:::

This function fetches historical messages of a channel.

It is possible to control how messages are returned and in what order, for example you can:

* Search for messages starting on the newest end of the timeline (default behavior - `reverse` = `false`)
* Search for messages from the oldest end of the timeline by setting `reverse` to `true`.
* Page through results by providing a `start` OR `end` timetoken.
* Retrieve a *slice* of the time line by providing both a `start` AND `end` timetoken.
* Limit the number of messages to a specific quantity using the `count` parameter.

:::tip Start & End parameter usage clarity
If only the `start` parameter is specified (without `end`), you will receive messages that are **older** than and up to that `start` timetoken value. If only the `end` parameter is specified (without `start`) you will receive messages that match that `end` timetoken value and **newer**. Specifying values for both `start` *and* `end` parameters will return messages between those timetoken values (inclusive on the `end` value). Keep in mind that you will still receive a maximum of 100 messages even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the `start` timetoken is necessary to page through the full set of results if more than 100 messages meet the timetoken values.
:::

### Method(s)

Use the following method(s) in the JavaScript SDK

```javascript
pubnub.history({
    channel: string,
    reverse: boolean,
    count: number,
    stringifiedTimeToken: boolean,
    includeMeta: boolean,
    start: string,
    end: string
})
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: stringDefault: n/a | Channel to return history messages from. |
| `reverse`Type: booleanDefault: `false` | Whether to traverse from oldest to newest. If both `start` and `end` are provided, `reverse` is ignored and messages return starting with the newest message. |
| `count`Type: numberDefault: `100` | Number of historical messages to return. Default/Maximum is `100`. |
| `stringifiedTimeToken`Type: booleanDefault: `false` | Whether to return timetokens as strings. |
| `includeMeta`Type: booleanDefault: n/a | Whether to include the meta object (if provided at publish time) in the response. |
| `start`Type: stringDefault: n/a | Timetoken delimiting the start (exclusive) of the time slice. |
| `end`Type: stringDefault: n/a | Timetoken delimiting the end (inclusive) of the time slice. |

:::tip Using the reverse parameter:
Messages are always returned sorted in ascending time direction from history regardless of `reverse`. The `reverse` direction matters when you have more than 100 (or `count`, if it's set) messages in the time interval, in which case `reverse` determines the end of the time interval from which it should start retrieving the messages.
:::

### Sample code

Retrieve the last 100 messages on a channel:

```javascript
try {
    const result = await pubnub.history({
        channel: "history_channel",
        count: 100, // how many items to fetch
        stringifiedTimeToken: true, // false is the default
    });
} catch (status) {
    console.log(status);
}
```

### Response

```javascript
// Example of Status
{
    error: false,
    operation: "PNHistoryOperation",
    statusCode: 200
}

// Example of Response
{
    endTimeToken: "14867650866860159",
    messages: [
        {
            timetoken: "14867650866860159",
            entry: "[User 636] hello World"
        },
        {...},
        {...},
        {...}
    ],
    startTimeToken: "14867650866860159"
}
```

### Other examples

#### Use history() to retrieve the three oldest messages by retrieving from the time line in reverse

```javascript
try {
    const result = await pubnub.history({
        channel: "my_channel",
        reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
        count: 3, // how many items to fetch
        stringifiedTimeToken: true, // false is the default
    });
} catch (status) {
    console.log(status);
}
```

#### Use history() to retrieve messages newer than a given timetoken by paging from oldest message to newest message starting at a single point in time (exclusive)

```javascript
try {
    const result = await pubnub.history({
        channel: "my_channel",
        reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
        stringifiedTimeToken: true, // false is the default
        start: "13406746780720711", // start timetoken to fetch
    });
} catch (status) {
    console.log(status);
}
```

#### Use history() to retrieve messages until a given timetoken by paging from newest message to oldest message until a specific end point in time (inclusive)

```javascript
try {
    const result = await pubnub.history({
        channel: "my_channel",
        stringifiedTimeToken: true, // false is the default
        end: "13406746780720711", // start timetoken to fetch
    });
} catch (status) {
    console.log(status);
}
```

#### History paging example

:::note Usage
You can call the method by passing nothing or a valid **timetoken** as the argument.
:::

```javascript
async function getAllMessages(initialTimetoken = 0) {
    const allMessages = [];
    let latestCount = 100;
    let timetoken = initialTimetoken;

    while (latestCount === 100) {
        const { messages, startTimeToken, endTimeToken } = await pubnub.history(
            {
                channel: "history_test",
                stringifiedTimeToken: true, // false is the default
                start: timetoken, // start timetoken to fetch
            }
        );

        latestCount = messages.length;
        timetoken = startTimeToken;

        if (messages && messages.length > 0) {
            allMessages.push(...messages);
        }
    }

    return allMessages;
}

// Usage examples:
// await getAllMessages();
// await getAllMessages("12345678901234");
```

#### Fetch messages with metadata

```javascript
try {
    const result = await pubnub.history({
        channel: "my_channel",
        stringifiedTimeToken: true,
        includeMeta: true,
    });
} catch (status) {
    console.log(status);
}
```

#### Sample code with promises

```javascript
pubnub.history({
    channel: 'history_channel',
    reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
    count: 100, // how many items to fetch
    stringifiedTimeToken: true, // false is the default
    start: '123123123123', // start timetoken to fetch
    end: '123123123133', // end timetoken to fetch
}).then((response) => {
    console.log(response);
}).catch((error) => {
    console.log(error);
});
```

## Terms in this document

* **Message** - A unit of data transmitted between clients or between a client and a server in PubNub, containing information such as text, binary data, or structured data formats like JSON. Messages are sent over channels and can be tracked for delivery and read status.
* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.
* **Timetoken** - A unique identifier for each message that represents the number of 100-nanosecond intervals since January 1, 1970, for example, 16200000000000000.