Unread messages

PubNub allows you to get a count of messages in channels that were published after a specific timestamp. When users return to their applications, the app can indicate which channels have new messages and also display counts of unread messages in each channel. You can build this feature easily so your users never miss a message and get the best chat experience.

There are two primary ways you can store a user's last-read timetokens:

  • Store timetoken cursors locally within the app
  • Store timetoken cursors on PubNub using Objects

Store cursors locally

With the first option, you'll need to store the timetoken of the last message that was read by the user in a channel. If the user uses multiple channels, you'll need to store multiple timetokens, one per channel.

Store cursors using Objects

With the second option, you can store these timetokens inside of PubNub. The Objects feature enables you to persist membership associations between users and channels, and any custom fields that might be useful for your app. Refer to Channel Metadata for more information on channel memberships.

Set channel cursors

Use the setMemberships method to store timetokens as custom fields on each user-channel membership on PubNub.

pubnub.objects.setMemberships({
channels: [{
id: "channel-1",
custom: {
lastReadTimetoken: 15518041524300120
},
{
id: "channel-2",
custom: {
lastReadTimetoken: 15518041524300251
}
}]
});

Get channel cursors

When the user returns to the app, use the getMemberships method to fetch channel memberships for the user along with its custom fields.

pubnub.objects.getMemberships({
include: {
customFields: true
}
});

The timetokens can then be passed to the messageCounts method.

Get counts of unread messages

The messageCounts method returns a count of unread messages in one or more channels. The count returned is the number of messages in storage with a timetoken value greater than or equal to the passed value in the timetoken parameter. For more details on retrieving counts of unread messages, refer to Getting Message Counts.

pubnub.messageCounts({
channels: ['ch-1', 'ch-2'],
channelTimetokens: ['15518041524300251'],
}, (status, results) => {
// handle status, response
console.log(status);
console.log(results);
});