Check user presence

PubNub allows you to track the online and offline status of users and devices in real time. This means that you can look up, among other things, who's currently online, when a user has joined/left a channel or which channels a user is subscribed to.

Subscription with Presence

You must create a subscription with Presence enabled to receive Presence events. For more information, refer to each SDK's Publish and Subscribe documentation.

The code below will print to the console a list of all users who are online on the chats.public.release_announcements channel.

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.

pubnub.hereNow(
{
channels: ["chats.public.release_announcements"]
},
function (status, response) {
console.log(status, response);
}
);

Checking presence is based on receiving presence events which are sent automatically from the PubNub servers when a user's state changes. You can react to these events by handling them using a handler dedicated to presence events.

Subscription with Presence

You must create a subscription with Presence enabled to receive Presence events. For more information, refer to each SDK's Publish and Subscribe documentation.

Presence events aren't sent on the channel where a change in presence happens. They're sent on a presence channel, which is a helper channel that gets created automatically for every regular channel.

If you know you will be interested in real-time presence changes, it's best to do it when you subscribe to the regular channel.

// subscribe to a single channel without presence
pubnub.subscribe({channels: ["chats_inbox.user_1905"]});

// subscribe to multiple channels with presence
pubnub.subscribe({
channels: [
"chats_guilds.mages_guild",
"alerts.system",
"geolocation.data"
],
withPresence: true
});

As a part of user presence, you can set a custom dynamic state, like current score or mood indicator, for the users in your channels. However, this state persists only as long as the user is subscribed to a channel. Once the user disconnects, that custom data is lost.

If you don't want to lose any additional data about your users and channels, consider adding metadata.

Last updated on
On this page