Message Persistence API for JavaScript SDK
fetchMessages(), deleteMessages(), and messageCounts().
Message Persistence must be enabled on the keyset before you store or read history, and new keysets don't enable it by default.
Each method returns a promise that resolves with the response and rejects with a PubNubError. The error carries a status object with category and statusCode, and status.errorData holds the details that PubNub returned for a failed request. Each method also takes a callback as the second argument, and with a callback the method returns nothing and PubNub calls it with (status, response). On success, status.error is false and status.operation names the operation, and on failure status.error is true and response is null. All examples use async/await, so wrap a call in try...catch to receive the error status.
The methods take channel ID strings, not SDK channel entities.
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)
Fetch history
Message Persistence add-on
This method requires that the Message Persistence add-on is enabled for your key in the Admin Portal.
Requires Message Persistence add-on
This method requires that the Message Persistence add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
fetchMessages() returns the messages that Message Persistence stores for one or more channels, using a PubNub client for JavaScript.
The start and end timetokens control which messages the call returns and in what order.
-
If you specify only
start, the call returns messages older than that timetoken, becausestartis the newer, exclusive boundary of the query. -
If you specify only
end, the call returns messages with a timetoken equal to or newer thanend, becauseendis the older, inclusive boundary of the query.
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:
startis the newer boundary (higher timetoken value) - search begins here, exclusiveendis the older boundary (lower timetoken value) - search stops here, inclusive
When you provide both parameters, start must be a higher timetoken than end.
Results are always returned in oldest-first order.
start to the timetoken of the oldest message in the previous response.channelsrequired#- IDs of the channels to fetch messages from, up to 500 channels. With
includeMessageActionsset totrue, pass one channel only. With more than one channel, the call rejects with aPubNubErrorwhosestatus.messagesays that history can return actions data for a single channel only. start#- Timetoken that sets the newer boundary of the query (exclusive). Retrieval begins at this timetoken and moves backward in time. With
end,startmust be a higher timetoken thanend. end#- Timetoken that sets the older boundary of the query (inclusive). Retrieval stops at this timetoken. With
start,endmust be a lower timetoken thanstart. count#- Number of messages to return for each channel. The default is
100for one channel, and25for several channels or withincludeMessageActionsset totrue. The SDK lowers a larger value to that default. includeMessageType#- Whether each returned message includes its PubNub message type in the
messageTypeproperty. includeCustomMessageType#- Whether each returned message includes the custom message type that its publisher set, in the
customMessageTypeproperty. A message carries it only when the publisher set one. For the background, see Message Persistence. includeUUID#- Whether each returned message includes the User ID of its publisher in the
uuidproperty. includeMeta#- Whether each returned message includes the metadata that its publisher set at publish time, in the
metaproperty. includeMessageActions#- Whether the response includes the message actions of each message, which limits the call to one channel and 25 messages. With more than one channel, the call rejects with a
PubNubErrorwhosestatus.messagesays that history can return actions data for a single channel only.
Sample code
Retrieve a message from a channel:
Returns
fetchMessages() resolves with channels, an object that maps each channel ID to an array of messages. With a callback, status.operation is PNFetchMessagesOperation. Each message has these properties:
channel#- ID of the channel that holds the message.
timetoken#- Timetoken that PubNub assigned to the message.
message#- Decrypted message payload.
messageType#- PubNub message type,
-1for a regular message and4for a file message. Present withincludeMessageType. customMessageType#- Custom message type that the publisher set. Present only when the publisher set one.
uuid#- User ID of the publisher. Present with
includeUUID. meta#- Metadata that the publisher set at publish time. Present only when the message has metadata.
actions#- Message actions on the message, grouped by action type and then by action value. Present with
includeMessageActionswhen the message has actions. error#- Decryption error. Present only when the SDK fails to decrypt the message, and
messagethen holds the undecrypted payload.
With includeMessageActions set to true, a response that PubNub truncates also has a more property. PubNub truncates when the returned messages hold more than 25000 message actions in total. To fetch the remaining messages, call fetchMessages() again with more.start as start and more.max as count.
The more property holds url, start, and max.
Other examples
Examples for Fetch history
Syntax
1pubnub.fetchMessages({
2 channels: string[],
3 start?: string,
4 end?: string,
5 count?: number,
6 includeMessageType?: boolean,
7 includeCustomMessageType?: boolean,
8 includeUUID?: boolean,
9 includeMeta?: boolean,
10 includeMessageActions?: boolean
11}): Promise<FetchMessagesResponse>;
Basic usage
1
1
Basic usage (React)
In React, call fetchMessages inside a useEffect hook on component mount and store the results in state to display them in your UI.
1
Returns
1{
2 "channels": {
3 "my-channel": [
4 {
5 "channel": "my-channel",
6 "timetoken": "15483367794816642",
7 "message": "message_1",
8 "messageType": -1,
9 "customMessageType": "text-message",
10 "uuid": "my-uuid"
11 }
12 ]
13 }
14}
Fetch messages with metadata and actions response
Fetch messages with metadata and actions response
1{
2 "channels": {
3 "my_channel": [
4 {
5 "channel": "my_channel",
6 "timetoken": "15741125155552287",
7 "message": { "text": "Hello world!" },
8 "messageType": -1,
9 "customMessageType": "your custom type",
10 "uuid": "someUserId",
11 "meta": {},
12 "actions": {
13 "reaction": {
14 "smiley_face": [
15 {
show all 30 linesDelete messages from history
Message Persistence add-on
This method requires that the Message Persistence add-on is enabled for your key in the Admin Portal.
Requires Message Persistence add-on
This method requires that the Message Persistence add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
deleteMessages() deletes stored messages from channel history, optionally within a time range, using a PubNub client for JavaScript.
Delete-From-History must be enabled for the keyset in the Admin Portal before a delete call succeeds. The JavaScript SDK also needs a secretKey in its configuration, and only the Node.js build signs requests with it. See Server operations.
The start timetoken is always the exclusive boundary and the end timetoken is always the inclusive boundary. The call deletes the message at end but not the message at start, whichever of the two values is larger. For the full walkthrough, see Delete messages from history.
channelrequired#- ID of the channel to delete messages from. The method takes the ID string, not an SDK channel entity.
start#- Timetoken that sets the exclusive boundary of the range to delete. The call keeps the message at this timetoken.
end#- Timetoken that sets the inclusive boundary of the range to delete. The call deletes the message at this timetoken.
Sample code
Returns
deleteMessages() resolves with an empty object, {}. With a callback, status.operation is PNDeleteMessagesOperation.
Other examples
Examples for Delete messages from history
Syntax
1pubnub.deleteMessages({
2 channel: string,
3 start?: string,
4 end?: string
5}): Promise<DeleteMessagesResponse>;
Basic usage
1
Delete a single message
Delete a single message
To delete one message, pass its publish timetoken, which a successful publish() returns, as end. Pass the next higher or the next lower timetoken as start. For example, if 15526611838554310 is the publish timetoken, pass 15526611838554310 as end and either 15526611838554309 or 15526611838554311 as start. Both pairs delete only the message at 15526611838554310.
Timetokens exceed the largest integer that a JavaScript Number represents exactly, so compute the neighboring timetoken with BigInt.
1
Message counts
Message Persistence add-on
This method requires that the Message Persistence add-on is enabled for your key in the Admin Portal.
Requires Message Persistence add-on
This method requires that the Message Persistence add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
messageCounts() returns the number of messages published to one or more channels since a timetoken, using a PubNub client for JavaScript.
messageCounts considers only messages published in the last 30 days.channelsrequired#- IDs of the channels to count messages in.
channelTimetokensrequired#- Timetokens from which to count messages, listed in the same order as
channels. A single timetoken applies to all channels. Any other list must hold one timetoken per channel. If the number of channels and timetokens differ and more than one timetoken is given, the call rejects with aPubNubErrorwhosestatus.messagesays that the lengths do not match.
Sample code
Returns
messageCounts() resolves with channels, an object that maps each channel ID to its message count. A channel without messages has a count of 0. A channel with 10,000 messages or more has a count of 10000. With a callback, status.operation is PNMessageCountsOperation.
Other examples
Examples for Message counts
Syntax
1pubnub.messageCounts({
2 channels: string[],
3 channelTimetokens: string[]
4}): Promise<MessageCountResponse>;
Basic usage
1
Returns
1{
2 "channels": {
3 "ch1": 49
4 }
5}
Count messages with a different timetoken for each channel
Count messages with a different timetoken for each channel
1
Deprecated history method
history() is a deprecated method of the PubNub JavaScript SDK that fetches the messages of one channel, and fetchMessages() replaces it.
The reference for apps that still call history() or read the deprecated data property of actions is Message Persistence API: deprecated history() method and actions data property for JavaScript SDK. New apps use Fetch history and read actions.