Presence API for PubNub JavaScript SDK
Presence enables you to track the online and offline status of users and devices in real-time and store custom state information. Presence provides authoritative information on:
- When a user has joined or left a channel
- Who, and how many, users are subscribed to a particular channel
- Which channel(s) an individual user is subscribed to
- Associated state information for these users
To learn more about Presence as a feature, visit 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.
Here Now
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
You can obtain information about the current state of a channel including a list of unique user-ids currently subscribed to the channel and the total occupancy count of the channel by calling the hereNow()
function in your application.
Cache
This method has a 3 second response cache time.
Method(s)
To call Here Now
, you can use the following method(s) in the JavaScript SDK:
pubnub.hereNow({
channels: Array<string> ,
channelGroups: Array<string> ,
includeUUIDs: boolean ,
includeState: boolean
}); Promise<HereNowResponse>
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
Operation Arguments | Hash | Yes | A hash of arguments. | |
channels | array<string> | Optional | Specifies the channel name to return occupancy results. You must specify either channels or channelGroups . | |
channelGroups | array<string> | Optional | The channel group for which here now information should be received. You must specify either channels or channelGroups . | |
includeUUIDs | boolean | Optional | true | Setting uuid to false disables the return of uuids. |
includeState | boolean | Optional | false | Setting state to true enables the return of subscriber state information. |
Basic Usage
Get a list of UUIDs subscribed to channel
try {
const result = await pubnub.hereNow({
channels: ["ch1"],
channelGroups: ["cg1"],
includeUUIDs: true,
includeState: true,
});
} catch (status) {
console.log(status);
}
Response
type hereNowResponse = {
totalChannels: number, // totalChannels = get total of channels
totalOccupancy: number, // totalOccupancy = get total of occupancies
channels: object // channels = get a map with values for each channel with uuids and states for each occupant of the channel
}
Other Examples
Returning State
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
try {
const result = await pubnub.hereNow({
channels: ["my_channel"],
includeState: true,
});
} catch (status) {
console.log(status);
}
Example Response
// Example of Status
{
"error": false,
"operation": "PNHereNowOperation",
"statusCode": 200
}
// Example of Response
{
"totalChannels": 1,
"totalOccupancy": 3,
"channels": {
"my_channel": {
"occupants": [
{
show all 35 linesReturn Occupancy Only
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
You can return only the occupancy
information for a single channel by specifying the channel and setting UUIDs
to false:
try {
const result = await pubnub.hereNow({
channels: ["my_channel"],
includeUUIDs: false,
});
} catch (status) {
console.log(status);
}
Example Response
// Example of Status
{
"error": false,
"operation": "PNHereNowOperation",
"statusCode": 200
}
// Example of Response
{
"totalChannels": 1,
"totalOccupancy": 3,
"channels": {
"my_channel": {
"occupants": [],
"name": "my_channel",
show all 19 linesChannel Group Usage
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
try {
const result = await pubnub.hereNow({
channelGroups: ["my_channel_group"],
});
} catch (status) {
console.log(status);
}
Example Response
// Example of Status
{
"error": false,
"operation": "PNHereNowOperation",
"statusCode": 200
}
// Example of Response
{
"totalChannels": 2,
"totalOccupancy": 3,
"channels": {
"my_channel_1": {
"occupants": [
{
show all 38 linesBasic usage with Promises
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
pubnub.hereNow({
channels: ["ch1"],
channelGroups : ["cg1"],
includeUUIDs: true,
includeState: true
}).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
});
Where Now
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
You can obtain information about the current list of channels to which a UUID is subscribed to by calling the whereNow
function in your application.
Timeout events
If the app is killed/crashes and restarted (or the page containing the PubNub instance is refreshed on the browser) within the heartbeat window no timeout event is generated.
Method(s)
To call whereNow
, you can use the following method(s) in the JavaScript SDK:
pubnub.whereNow({
uuid: string
}): Promise<WhereNowResponse>
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
Operation Arguments | Hash | Yes | A hash of arguments. | |
uuid | string | Optional | current uuid | Specifies the uuid to return channel list for. |
Basic Usage
You simply need to define the uuid
to be used to send the data to as in the example below.
Get a list of channels a UUID is subscribed to
try {
const result = await pubnub.whereNow({
uuid: "uuid",
});
} catch (status) {
console.log(status);
}
Response
// Example of Status
{
error: false,
operation: "PNWhereNowOperation",
statusCode: 200
}
// Example of Response
{
"channels": ["ch1", "ch2"]
}
Other Examples
Basic usage with Promises
pubnub.whereNow({
uuid: "uuid"
}).then((response) => {
console.log(response);
}).catch((error) => {
console.log(error);
});
User State
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
The state API is used to set/get key/value pairs specific to a subscriber uuid
.
State information is supplied as a JSON object of key/value pairs.
Method(s)
Set State
pubnub.setState({
channels: Array<string> ,
channelGroups: Array<string> ,
state: any
}): Promise<SetStateResponse>;
Parameter | Type | Required | Description |
---|---|---|---|
Operation Arguments | Hash | Yes | A hash of arguments. |
channels | Array | Optional | Either channels or channelGroups should be provided, Specifies the channels to set the state. |
channelGroups | Array | Optional | Either channels or channelGroups should be provided, Specifies the Channel Group to set the state |
state | any | Optional | JSON object of key/value pairs with supported data-types of int, float and string. Nesting of key/values is not permitted and key names beginning with prefix pn are reserved. If the state parameter is undefined, the current state for the specified uuid will be returned. If a specified key already exists for the uuid it will be over-written with the new value. Key values can be deleted by setting the particular value to null . |
Get State
pubnub.getState({
uuid: string,
channels: Array<string>,
channelGroups: Array<string>
}): Promise<GetStateResponse>;
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
Operation Arguments | Hash | Yes | A hash of arguments. | |
uuid | String | Optional | current uuid | The subscriber uuid to get the current state. |
channels | Array | Optional | Either channels or channelGroups should be provided, Specifies the channels to get the state. | |
channelGroups | Array | Optional | Either channels or channelGroups should be provided, Specifies the Channel Group to get the state. |
Basic Usage
Set State
try {
const result = await pubnub.setState({
state: newState,
channels: ["ch1"],
channelGroups: ["cg1"],
});
} catch (status) {
console.log(status);
}
Get State
try {
const result = await pubnub.getState({
uuid: "uuid",
channels: ["ch1"],
channelGroups: ["cg1"],
});
} catch (status) {
console.log(status);
}
Response
Set State
// Example of Status
{
error: false,
operation: "PNSetStateOperation",
statusCode: 200
}
// Example of Response
{
state: {
me: 'typing'
}
}
Get State
// Example of Status
{
error: false,
operation: "PNGetStateOperation",
statusCode: 200
}
// Example of Response
{
channels: {
ch1: {
me: 'typing'
}
}
}
Other Examples
Set State Basic usage with Promises
pubnub.setState({
state: newState,
channels: ['ch1'],
channelGroups: ['cg1']
}).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
});
Get State Basic usage with Promises
pubnub.getState({
uuid: "uuid",
channels: ['ch1'],
channelGroups: ['cg1']
}).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
});