Presence State

You can set dynamic, custom state for users on one or more channels. PubNub stores this state on each channel while the user remains subscribed.

Typical examples include score, game status, or frequently changing location.

The state is transient. PubNub does not persist it. When the client disconnects, the state is cleared. If you need a user's state after reconnect, cache it locally. For long‑term storage, see App Context.

PubNub also sends presence state-change events when the user's state changes. Subscribe to presence channels to receive these events. See Presence Events.

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.

Set Presence state

You can set state for a User ID on channel(s) or channel group(s). By default, PubNub uses the current client's User ID. When you set state on a channel group, PubNub applies it to all channels in that group.

pubnub.setState(
{
state: {"mood":"pumped", "isTyping":false},
channels: ["chats.room1"],
channelGroups: ["cg_user123_friends"]
},
function (status, response) {
if (status.isError) {
console.log(status);
}
else {
console.log(response);
}
}
);

When you set state for a client, PubNub overwrites the entire existing state. To update part of the state, send the full state payload. Keep state payloads small for efficiency.

Get Presence state

You can get state data for any client on a given channel(s) or channel group(s) using the Get State API. This is useful to get the state of other clients based on their User ID.

pubnub.getState(
{
uuid: "anotherClientUserID",
channels: ["chats.room1"],
channelGroups: ["cg_user123_friends"]
},
function (status, response) {
// handle status, response
}
);
Last updated on