Presence
Presence is a powerful feature that allows clients to be aware of other participants currently active on a channel. Each participant in a channel is uniquely identified by:
- A self-assigned client identifier
- A system-assigned connection identifier
- An optional payload for additional status or attribute information
This feature is particularly useful for rapidly developing real-time applications such as:
- Chat rooms
- Multiplayer games
- Collaborative tools
Presence automatically tracks and updates the status of all participants across various devices in real-time, simplifying the development of interactive, multi-user applications.
Accessing Presence
The presence feature is accessed through the participant
property of a channel. Once you have connected to a channel, you can interact with the presence functionality as follows:
const channel = await realtime.connect('channel-name');
const presence = channel.participant;
Updating Presence
To update your presence information, use the update()
method. This allows you to set or modify any custom data associated with your presence:
channel.participant.update({ name: "John", status: "online" });
Subscribing to Presence Events
You can subscribe to presence events to receive updates about participants joining, leaving, or updating their status. Use the subscribe()
method with the appropriate event type:
const callback = ({ data }) => {
console.log("Presence update", data);
};
channel.participant.subscribe("presence.update", callback);
Available presence events are:
presence.joined-room
: Triggered when a participant joins the channelpresence.leave
: Triggered when a participant leaves the channelpresence.update
: Triggered when a participant updates their presence data
Unsubscribing from Presence Events
To stop receiving updates for a specific presence event, use the unsubscribe()
method:
channel.participant.unsubscribe("presence.update");
Getting All Presence Information
To retrieve the current presence information for all participants in the channel, use the getAll()
method:
const presences = channel.participant.getAll();
console.log(presences);
This method returns an array containing presence information for all participants in the channel. Here's an example of what the returned data might look like:
[
{
"connectionId": "80NFb-QRx3UljIIdADWo",
"data": {
"mostHatedCandy": "Bit-O-Honey",
"favoriteCandy": "Chocolate"
},
"id": "luke-long",
"name": "Luke Long",
"timestamp": 1728668099104
}
]
In this example:
connectionId
is the unique identifier for this participant's connectiondata
contains custom information set by the participantid
is the participant's unique identifiername
is the participant's nametimestamp
is the Unix timestamp of when this presence information was last updated
You can use this data to display information about current participants in your application, such as a list of active users or their current status.