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
Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
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#- Channel names to return the occupancy and occupants of. When
channelsandchannelGroupsare both empty, the SDK requests the occupancy of every channel on the key and ignoreslimitandoffset. channelGroups#- Channel group names to return the occupancy and occupants of. Wildcards are not supported.
includeUUIDs#- Whether the response lists the User IDs of the occupants of each channel. Set to
falseto receive only the occupancy counts. includeState#- Whether the response includes the presence state of each occupant.
limit#Here Nowaccepts alimitof up to 1,000 occupants per channel, and you paginate past that withoffset. Settinglimitto0returns only the occupancy count, without the list of occupants.offset#- Zero-based position of the first occupant to return. Use it with
limitto page through the occupants of a channel. The SDK omitsoffsetfrom the request when it is0or not set.
Sample code
Returns
hereNow() resolves with the total channel count, the total occupancy, and the occupants of each channel.
Other examples
Examples for Here now
Syntax
1pubnub.hereNow({
2 channels?: string[],
3 channelGroups?: string[],
4 includeUUIDs?: boolean,
5 includeState?: boolean,
6 limit?: number,
7 offset?: number
8}): Promise<HereNowResponse>;
Get a list of UUIDs subscribed to channel
Get a list of UUIDs subscribed to channel
1import PubNub from 'pubnub';
2// Initialize PubNub with your keys
3const pubnub = new PubNub({
4 publishKey: 'YOUR_PUBLISH_KEY',
5 subscribeKey: 'YOUR_SUBSCRIBE_KEY',
6 userId: 'YOUR_USER_ID',
7});
1// Function to get presence information for a channel
2const result = await pubnub.hereNow({
3 channels: ['ch1'],
4 channelGroups: ['cg1'],
5 includeUUIDs: true,
6 includeState: true,
7});
8console.log('Here Now Result:', result);
Basic usage (React)
1import React, { useState, useEffect } from 'react';
2import PubNub from 'pubnub';
3
4const pubnub = new PubNub({
5 publishKey: 'YOUR_PUBLISH_KEY',
6 subscribeKey: 'YOUR_SUBSCRIBE_KEY',
7 userId: 'YOUR_USER_ID',
8});
9
10function ChannelOccupancy() {
11 const [occupancy, setOccupancy] = useState(null);
12 const [onlineUsers, setOnlineUsers] = useState([]);
13
14 useEffect(() => {
15 async function fetchPresence() {
show all 42 linesReturns
1type HereNowResponse = {
2 totalChannels: number,
3 totalOccupancy: number,
4 channels: {
5 [channel: string]: {
6 name: string,
7 occupancy: number,
8 occupants: { uuid: string, state?: Payload | null }[]
9 }
10 }
11}
Returning state
Returning state
1const response = await pubnub.hereNow({
2 channels: ['my_channel'],
3 includeState: true,
4});
5console.log('hereNow response:', response);
Returning state - Example response
Example response
1// Example of Status
2{
3 "error": false,
4 "operation": "PNHereNowOperation",
5 "statusCode": 200
6}
7
8// Example of Response
9{
10 "totalChannels": 1,
11 "totalOccupancy": 3,
12 "channels": {
13 "my_channel": {
14 "occupants": [
15 {
show all 35 linesReturn occupancy only
Return occupancy only
1const response = await pubnub.hereNow({
2 channels: ['my_channel'],
3 includeUUIDs: false,
4});
5console.log('hereNow response:', response);
Return occupancy only - Example response
Example response
1// Example of Status
2{
3 "error": false,
4 "operation": "PNHereNowOperation",
5 "statusCode": 200
6}
7
8// Example of Response
9{
10 "totalChannels": 1,
11 "totalOccupancy": 3,
12 "channels": {
13 "my_channel": {
14 "occupants": [],
15 "name": "my_channel",
show all 19 linesChannel group usage
Channel group usage
1const response = await pubnub.hereNow({
2 channelGroups: ['my_channel_group'],
3});
4console.log('hereNow response:', response);
Channel group usage - Example response
Example response
1// Example of Status
2{
3 "error": false,
4 "operation": "PNHereNowOperation",
5 "statusCode": 200
6}
7
8// Example of Response
9{
10 "totalChannels": 2,
11 "totalOccupancy": 3,
12 "channels": {
13 "my_channel_1": {
14 "occupants": [
15 {
show all 38 linesSample code with promises
Sample code with promises
1pubnub
2 .hereNow({
3 channels: ['ch1'],
4 channelGroups: ['cg1'],
5 includeUUIDs: true,
6 includeState: true,
7 })
8 .then((response) => {
9 console.log(response);
10 })
11 .catch((error) => {
12 console.log(error);
13 });
Where now
Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
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#- User ID to list the channels of. When omitted, the SDK uses the
userIdof the PubNub client.
Sample code
Returns
whereNow() resolves with the IDs of the channels where the user is present.
Examples for Where now
Syntax
1pubnub.whereNow({
2 uuid?: string
3}): Promise<WhereNowResponse>;
Get a list of channels a UUID is subscribed to
Get a list of channels a UUID is subscribed to
1const response = await pubnub.whereNow({
2 uuid: 'uuid',
3});
4console.log('whereNow response:', response);
Basic usage (React)
1import React, { useState, useEffect } from 'react';
2import PubNub from 'pubnub';
3
4const pubnub = new PubNub({
5 publishKey: 'YOUR_PUBLISH_KEY',
6 subscribeKey: 'YOUR_SUBSCRIBE_KEY',
7 userId: 'YOUR_USER_ID',
8});
9
10function UserChannels() {
11 const [channels, setChannels] = useState([]);
12
13 useEffect(() => {
14 async function fetchChannels() {
15 try {
show all 35 linesReturns
1// Example of Status
2{
3 error: false,
4 operation: "PNWhereNowOperation",
5 statusCode: 200
6}
7
8// Example of Response
9{
10 "channels": ["ch1", "ch2"]
11}
Set state
Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
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.
channels#- Channel names to set the presence state on. Provide
channels,channelGroups, or both. A call with neither fails validation with the messagePlease provide a list of channels and/or channel-groups. channelGroups#- Channel group names to set the presence state on. Wildcards are not supported.
staterequired#- Presence state to set, as a JSON-serializable object. A call with
stateundefined fails validation with the messageMissing State.
With maintainPresenceState and enableEventEngine both true, the SDK sends the state again with later subscribe handshakes and presence heartbeats. See Configuration.
Sample code
Returns
setState() resolves with the state that PubNub stored for the user.
Examples for Set state
Syntax
1pubnub.setState({
2 channels?: string[],
3 channelGroups?: string[],
4 state: Payload
5}): Promise<SetPresenceStateResponse>;
Basic usage
1const response = await pubnub.setState({
2 state: { status: 'online' },
3 channels: ['ch1'],
4 channelGroups: ['cg1'],
5});
6console.log('State set successfully:', response);
Basic usage (React)
1import React, { useEffect, useState } from 'react';
2import PubNub from 'pubnub';
3
4const pubnub = new PubNub({
5 publishKey: 'YOUR_PUBLISH_KEY',
6 subscribeKey: 'YOUR_SUBSCRIBE_KEY',
7 userId: 'YOUR_USER_ID',
8});
9
10function UserWithPresenceState() {
11 const [isStateSet, setIsStateSet] = useState(false);
12
13 useEffect(() => {
14 async function setPresenceState() {
15 try {
show all 30 linesReturns
1// Example of Status
2{
3 error: false,
4 operation: "PNSetStateOperation",
5 statusCode: 200
6}
7
8// Example of Response
9{
10 state: {
11 me: 'typing'
12 }
13}
Get state
Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
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.
Sample code
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.
Examples for Get state
Syntax
1pubnub.getState({
2 uuid?: string,
3 channels?: string[],
4 channelGroups?: string[]
5}): Promise<GetPresenceStateResponse>;
Basic usage
1const response = await pubnub.getState({
2 uuid: 'uuid',
3 channels: ['ch1'],
4 channelGroups: ['cg1'],
5});
6console.log('State retrieved successfully:', response);
Basic usage (React)
1import React, { useState, useEffect } from 'react';
2import PubNub from 'pubnub';
3
4const pubnub = new PubNub({
5 publishKey: 'YOUR_PUBLISH_KEY',
6 subscribeKey: 'YOUR_SUBSCRIBE_KEY',
7 userId: 'YOUR_USER_ID',
8});
9
10function UserState() {
11 const [presenceState, setPresenceState] = useState(null);
12
13 useEffect(() => {
14 async function fetchState() {
15 try {
show all 29 linesReturns
1// Example of Status
2{
3 error: false,
4 operation: "PNGetStateOperation",
5 statusCode: 200
6}
7
8// Example of Response for one channel and no channel groups
9{
10 channels: {
11 ch1: {
12 me: 'typing'
13 }
14 }
15}
show all 26 linesReceive 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.
Sample code
Examples for Receive presence events
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 linesBasic usage (React)
1import React, { useState, useEffect } from 'react';
2import PubNub from 'pubnub';
3
4const pubnub = new PubNub({
5 publishKey: 'YOUR_PUBLISH_KEY',
6 subscribeKey: 'YOUR_SUBSCRIBE_KEY',
7 userId: 'YOUR_USER_ID',
8});
9
10function PresenceTracker() {
11 const [onlineUsers, setOnlineUsers] = useState([]);
12 const [occupancy, setOccupancy] = useState(0);
13
14 useEffect(() => {
15 pubnub.addListener({
show all 48 lines