On this page

Message Persistence API for JavaScript SDK

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.

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)
Supported and recommended asynchronous patterns

PubNub supports Callbacks, Promises, and Async/Await 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 syntax in your code.

Fetch history

Requires Message Persistence

Enable Message Persistence for your key in the Admin Portal. See how to enable add-on features.

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 start, you receive messages older than that timetoken. start is the newer boundary of the query (exclusive).
  • If you specify only end, you receive messages newer than or equal to that timetoken. end is the older boundary of the query (inclusive).
  • If you specify both start and end, start must be a higher timetoken than end. Results contain messages between those timetokens, excluding the message at start and including the message at end.
How to use the start and end parameters

PubNub retrieves messages by searching backward through time (newest to oldest). Because of this, the parameter names are the reverse of their intuitive meaning:

  • start is the newer boundary (higher timetoken value) - search begins here, exclusive
  • end is the older boundary (lower timetoken value) - search stops here, inclusive

When you provide both parameters, start must be a higher timetoken than end.

9:00 AM10:00 AM11:00 AM11:59 AM

Results are always returned in oldest-first order.

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:

1pubnub.fetchMessages({
2 channels: Array<string>,
3 count: number,
4 includeMessageType: boolean,
5 includeCustomMessageType: boolean,
6 includeUUID: boolean,
7 includeMeta: boolean,
8 includeMessageActions: boolean,
9 start: string,
10 end: string
11})
* required
ParameterDescription
channels *
Type: Array<string>
Default:
n/a
Channels to fetch history messages from (up to 500).
count
Type: number
Default:
100 or 25
Number of historical messages to return per channel. Default is 100 (single) and 25 (multi) or 25 with includeMessageActions.
includeMessageType
Type: boolean
Default:
true
Whether to pass true to include message type. Default is true.
includeCustomMessageType
Type: Boolean
Default:
n/a
Whether to retrieve messages with the custom message type.

For more information, refer to Retrieving Messages.
includeUUID
Type: boolean
Default:
true
Whether to receive the publisher uuid. Default is true.
includeMeta
Type: boolean
Default:
n/a
Whether to include the meta object (if provided at publish time) in the response.
includeMessageActions
Type: boolean
Default:
n/a
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
Type: string
Default:
n/a
Newer boundary of the query (exclusive). Retrieval begins at this timetoken and moves backward in time. Must be a higher timetoken value than end when both are provided.
end
Type: string
Default:
n/a
Older boundary of the query (inclusive). Retrieval stops at this timetoken. Must be a lower timetoken value than start when both are provided.
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

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:

1

1

Response

1//Example of status
2{
3 error: false,
4 operation: 'PNFetchMessagesOperation',
5 statusCode: 200
6}
7
8//Example of response
9{
10 "channels":{
11 "my-channel":[
12 {
13 "message":"message_1",
14 "timetoken":"15483367794816642",
15 "uuid":"my-uuid",
show all 23 lines

Other examples

Fetch messages with metadata and actions

1

Fetch messages with metadata and actions response

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.

1// Example of status
2{
3 "error": false,
4 "operation": "PNFetchMessagesOperation",
5 "statusCode": 200
6}
7
8// Example of response
9{
10 "channels":{
11 "my_channel":[
12 {
13 "channel : "my_channel",
14 "timetoken":"15741125155552287",
15 "message":{
show all 40 lines

Delete messages from history

Requires Message Persistence

Enable Message Persistence for your key in the Admin Portal. See how to enable add-on features.

Remove messages from the history of a specific channel.

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.

1pubnub.deleteMessages({
2 channel: string,
3 start: string,
4 end: string
5})
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.

How to use the start and end parameters

PubNub retrieves messages by searching backward through time (newest to oldest). Because of this, the parameter names are the reverse of their intuitive meaning:

  • start is the newer boundary (higher timetoken value) - search begins here, exclusive
  • end is the older boundary (lower timetoken value) - search stops here, inclusive

When you provide both parameters, start must be a higher timetoken than end.

9:00 AM10:00 AM11:00 AM11:59 AM

Results are always returned in oldest-first order.

* required
ParameterDescription
channel *
Type: string
Specifies channel messages to be deleted from history.
start
Type: string
Newer boundary of the query (exclusive). Must be a higher timetoken value than end when both are provided.
end
Type: string
Older boundary of the query (inclusive). Must be a lower timetoken value than start when both are provided.

Sample code

1

Response

1{
2 error: false,
3 operation: 'PNDeleteMessagesOperation',
4 statusCode: 200
5}

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.

1

Message counts

Requires Message Persistence

Enable Message Persistence for your key in the Admin Portal. See how to enable add-on features.

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.

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:

1pubnub.messageCounts({
2 channels: Array<string>,
3 channelTimetokens: Array<string>
4})
* required
ParameterDescription
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

1

Returns

Message count

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

1{
2 channels: {
3 ch1: 49
4 }
5}

Status response

1{
2 error: false,
3 operation: 'PNMessageCountsOperation',
4 statusCode: 200
5}

Other examples

Retrieve count of messages using different timetokens for each channel

1

History (deprecated)

Requires Message Persistence

Enable Message Persistence for your key in the Admin Portal. See how to enable add-on features.

Alternative method

This method is deprecated. Use 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.

Method(s)

Use the following method(s) in the JavaScript SDK

1pubnub.history({
2 channel: string,
3 reverse: boolean,
4 count: number,
5 stringifiedTimeToken: boolean,
6 includeMeta: boolean,
7 start: string,
8 end: string
9})
* required
ParameterDescription
channel *
Type: string
Default:
n/a
Channel to return history messages from.
reverse
Type: boolean
Default:
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: number
Default:
100
Number of historical messages to return. Default/Maximum is 100.
stringifiedTimeToken
Type: boolean
Default:
false
Whether to return timetokens as strings.
includeMeta
Type: boolean
Default:
n/a
Whether to include the meta object (if provided at publish time) in the response.
start
Type: string
Default:
n/a
Newer boundary of the query (exclusive). Retrieval begins at this timetoken and moves backward in time. Must be a higher timetoken value than end when both are provided.
end
Type: string
Default:
n/a
Older boundary of the query (inclusive). Retrieval stops at this timetoken. Must be a lower timetoken value than start when both are provided.
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:

1try {
2 const result = await pubnub.history({
3 channel: "history_channel",
4 count: 100, // how many items to fetch
5 stringifiedTimeToken: true, // false is the default
6 });
7} catch (status) {
8 console.log(status);
9}

Response

1// Example of Status
2{
3 error: false,
4 operation: "PNHistoryOperation",
5 statusCode: 200
6}
7
8// Example of Response
9{
10 endTimeToken: "14867650866860159",
11 messages: [
12 {
13 timetoken: "14867650866860159",
14 entry: "[User 636] hello World"
15 },
show all 21 lines

Other examples

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

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

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)

1try {
2 const result = await pubnub.history({
3 channel: "my_channel",
4 reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
5 stringifiedTimeToken: true, // false is the default
6 start: "13406746780720711", // start timetoken to fetch
7 });
8} catch (status) {
9 console.log(status);
10}

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)

1try {
2 const result = await pubnub.history({
3 channel: "my_channel",
4 stringifiedTimeToken: true, // false is the default
5 end: "13406746780720711", // start timetoken to fetch
6 });
7} catch (status) {
8 console.log(status);
9}

History paging example

Usage

You can call the method by passing nothing or a valid timetoken as the argument.

1async function getAllMessages(initialTimetoken = 0) {
2 const allMessages = [];
3 let latestCount = 100;
4 let timetoken = initialTimetoken;
5
6 while (latestCount === 100) {
7 const { messages, startTimeToken, endTimeToken } = await pubnub.history(
8 {
9 channel: "history_test",
10 stringifiedTimeToken: true, // false is the default
11 start: timetoken, // start timetoken to fetch
12 }
13 );
14
15 latestCount = messages.length;
show all 28 lines

Fetch messages with metadata

1try {
2 const result = await pubnub.history({
3 channel: "my_channel",
4 stringifiedTimeToken: true,
5 includeMeta: true,
6 });
7} catch (status) {
8 console.log(status);
9}

Sample code with promises

1pubnub.history({
2 channel: 'history_channel',
3 reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
4 count: 100, // how many items to fetch
5 stringifiedTimeToken: true, // false is the default
6 start: '123123123123', // start timetoken to fetch
7 end: '123123123133', // end timetoken to fetch
8}).then((response) => {
9 console.log(response);
10}).catch((error) => {
11 console.log(error);
12});