Presence enables you to track the online and offline status of users and devices in real time and store custom state information. When you have Presence enabled, PubNub automatically creates a presence channel for each channel. Subscribing to a presence channel or presence channel group will only return presence events.
For more details on working with presence, refer to the Presence tutorial.
Get online users in a space
hereNow() method to obtain information about the current state of a space, including a list of unique users currently subscribed to the space.
Get occupancy of users in a space
hereNow() method to get a count of online users in a space. The count includes unique users who are subscribed to the space.
PubNub also triggers presence events as users come online or go offline from the application. These events can be received either directly by the clients or by a server using webhooks to keep a user's online/offline status up to date.
|join||fires when a user subscribes to a channel.|
|leave||fires when a user unsubscribes from a channel.|
|timeout||fires when a connection to a channel is severed and the subscriber hasn't been seen in 320 seconds (just over 5 minutes).|
|state-change||fires anytime the user's state is changed using the state API (function signature varies by SDK).|
|interval||fires to provide an occupancy count. The default setting for the Presence Interval property is 10 seconds, which is configurable on your PubNub Dashboard's Presence add-on panel.|
Add Presence Listeners
To receive presence events directly on the clients, add presence event listeners from the SDK.
Subscribe to Presence Channels
Once presence listeners are added, call subscribe with
withPresence flag enabled to receive presence events. You can also directly subscribe to presence channels by adding
-pnpres to the original channel name.
Use presence webhooks
Presence webhooks provide a means for your server to be notified whenever presence events occur on any channel for your keys. This provides a scalable solution for your server-side application to monitor presence events.
Before you implement the REST endpoints, it's helpful to know what the events' data looks like (content-type is
application/json). Here is an example of a
The JSON payload is the same for
state-change, other than the value of the
action object. You would only include the
data object if there was state data involved, but this is everything you need to consider.
For active and inactive, the content-type is
The value of
status will be either
Once your server's REST endpoints are implemented and the PubNub key configuration is in place, you're ready to go.
You may find it useful to provide separate endpoints for active/inactive and join/leave/timeout/state-change events, but there is no requirement to do so.