Presence API for JavaScript SDK

The Presence API of the PubNub SDK for JavaScript reports which users are online on a channel, which channels a user is on, and the presence state of users. To learn more about Presence as a feature, see the Presence overview.

Supported and recommended asynchronous patterns

PubNub supports Callbacks, Promises, and Async/Await for asynchronous JS operations. The recommended pattern is Async/Await and all sample requests in this document are based on it. This pattern returns a status only on detecting an error. To receive the error status, you must add the try...catch syntax to your code.

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.

Here now​

hereNow() returns the User IDs that are present on channels and channel groups, and the occupancy of each channel, with a PubNub client for JavaScript.

When Access Manager is enabled, calling Here Now requires read permission on the queried channel.

channels#
Type: string[]
Default: no default
Channel names to return the occupancy and occupants of. When channels and channelGroups are both empty, the SDK requests the occupancy of every channel on the key and ignores limit and offset.
channelGroups#
Type: string[]
Default: no default
Channel group names to return the occupancy and occupants of. Wildcards are not supported.
includeUUIDs#
Type: boolean
Default: true
Whether the response lists the User IDs of the occupants of each channel. Set to false to receive only the occupancy counts.
includeState#
Type: boolean
Default: false
Whether the response includes the presence state of each occupant.
limit#
Type: number
Default: 1000
Here Now accepts a limit of up to 1,000 occupants per channel, and you paginate past that with offset. Setting limit to 0 returns only the occupancy count, without the list of occupants.
offset#
Type: number
Default: no default
Zero-based position of the first occupant to return. Use it with limit to page through the occupants of a channel. The SDK omits offset from the request when it is 0 or not set.

Returns​

hereNow() resolves with the total channel count, the total occupancy, and the occupants of each channel.

Syntax

1pubnub.hereNow({
2 channels?: string[],
3 channelGroups?: string[],
4 includeUUIDs?: boolean,
5 includeState?: boolean,
6 limit?: number,
7 offset?: number
8}): Promise<HereNowResponse>;

Where now​

whereNow() returns the channels that a User ID is present on, with a PubNub client for JavaScript.

Where Now requires no channel-level permission when Access Manager is enabled because it looks up a User ID rather than a channel.

uuid#
Type: string
Default: no default
User ID to list the channels of. When omitted, the SDK uses the userId of the PubNub client.

Returns​

whereNow() resolves with the IDs of the channels where the user is present.

Syntax

1pubnub.whereNow({
2 uuid?: string
3}): Promise<WhereNowResponse>;

Set state​

setState() sets the presence state of the current User ID of a PubNub client for JavaScript on channels and channel groups.

Presence state is custom data, such as a score, a game state, or a location. PubNub holds it for a User ID on a channel while the User ID stays subscribed. PubNub doesn't persist presence state, and disconnecting a client clears it. Setting presence state overwrites the entire existing state of the User ID on that channel, so send the full state object, not only the field that changed. To learn more, see Set and get presence state.

When Access Manager is enabled, Get State and Set State both require read permission on the channel.

required
channels#
Type: string[]
Default: no default
Channel names to set the presence state on. Provide channels, channelGroups, or both. A call with neither fails validation with the message Please provide a list of channels and/or channel-groups.
channelGroups#
Type: string[]
Default: no default
Channel group names to set the presence state on. Wildcards are not supported.
state required#
Type: Payload
Default: no default
Presence state to set, as a JSON-serializable object. A call with state undefined fails validation with the message Missing State.

With maintainPresenceState and enableEventEngine both true, the SDK sends the state again with later subscribe handshakes and presence heartbeats. See Configuration.

Returns​

setState() resolves with the state that PubNub stored for the user.

Syntax

1pubnub.setState({
2 channels?: string[],
3 channelGroups?: string[],
4 state: Payload
5}): Promise<SetPresenceStateResponse>;

Get state​

getState() reads the presence state of a User ID on channels and channel groups, using a PubNub client for JavaScript.

Presence state is custom data, such as a score, a game state, or a location. PubNub holds it for a User ID on a channel while the User ID stays subscribed. PubNub doesn't persist presence state, and disconnecting a client clears it. To learn more, see Set and get presence state.

When Access Manager is enabled, Get State and Set State both require read permission on the channel.

uuid#
Type: string
Default: no default
User ID to read the presence state of. When omitted, the SDK uses the userId of the PubNub client.
channels#
Type: string[]
Default: no default
Channel names to read the presence state from. Provide channels, channelGroups, or both.
channelGroups#
Type: string[]
Default: no default
Channel group names to read the presence state from. Wildcards are not supported.

Returns​

getState() resolves with the state of the user, grouped by channel.

With one channel and no channel groups, channels holds the state of that channel directly. With several channels or any channel group, the state of each channel sits one level deeper, in channels.channels.

Syntax

1pubnub.getState({
2 uuid?: string,
3 channels?: string[],
4 channelGroups?: string[]
5}): Promise<GetPresenceStateResponse>;

Receive presence events​

receivePresenceEvents: true makes a subscription in the JavaScript SDK deliver join, leave, timeout, interval and state-change events to a presence listener.

Presence events require the Presence add-on to be enabled for your key. Every presence event has action, channel, subscription, timetoken and timestamp. Events for join, leave and timeout add uuid and occupancy. A state-change event adds uuid and state, and has no occupancy. An interval event adds occupancy and the optional lists join, leave and timeout.

Up to the Announce Max threshold, a channel emits individual join, leave, and timeout events. Above it, the channel emits periodic interval events instead, while state-change stays individual in both modes.

To learn more about subscriptions and event listeners, see Publish & Subscribe.

Basic usage

1// create a subscription from a channel entity
2const channel = pubnub.channel('channel_1');
3const subscription1 = channel.subscription({ receivePresenceEvents: true });
4
5// create a subscription set with multiple channels
6const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] });
7
8// add a status listener
9pubnub.addListener({
10 status: (s) => {
11 console.log('Status', s.category);
12 },
13});
14
15// add message and presence listeners
show all 33 lines

Was this page useful?

Last updated on