Check user presence

PubNub lets you track the online and offline status of users and devices in real time. You can see who is online, when a user joins or leaves a channel, and which channels a user is subscribed to. Learn the basics in Presence fundamentals.

Subscription with Presence

To receive Presence events, you subscribe with Presence and have Presence enabled on your keyset. Make sure you configure Presence to track Presence-related events for all or selected channels (through Presence Management rules).

Before you begin, make sure you have initialized PubNub with your keys. The code below prints 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);
}
);

Presence relies on presence events that PubNub sends automatically when a user’s state changes. You can react to these events by adding a handler dedicated to presence events.

Subscription with Presence

To receive Presence events, you subscribe with Presence and have Presence enabled on your keyset. Make sure you configure Presence to track Presence-related events for all or selected channels (through Presence Management rules).

PubNub sends presence events on a presence channel, not on the channel where the change happens. A presence channel is created automatically for every regular channel.

If you need real‑time presence changes, enable presence 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 part of user presence, you can set a custom dynamic state, such as a score or mood indicator, for users in your channels. This state persists only while the user is subscribed to a channel. When the user disconnects, the custom data is removed.

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

Last updated on
On this page