Skip to content
Documentation
API
Presence

Class: Presence

The Presence class manages the connection between the browser and the backend server, supporting both WebTransport and WebSocket at the same time.

createPresence(url[,option])

This method creates a new instance of the Presence class. It takes in two parameters:

  • url: The endpoint of the backend service which client connect to.
  • option:
    • publicKey: The authentication string to connect to backend.
    • id: Current user client id.
    • debug: default is false, set to true to logs to browser's Dev Tools.
    • autoDowngrade: default is false, set to true will try to connect by WebSocket after WebTransport connection creation failed.
  • Return: <Promise> containing Presence object.

Create a Presence instance which manage the connection from browser to backend.

Note that WebTransport is the default transport for Presencejs, but there are two scenarios where users can not enjoy it:

  1. User's web browser is other than Chrome or Microsoft Edge.
  2. User's network condition limited UDP connections.

Presencejs detects these situations automatically. When autoDowngrade is turned on, it will retry connecting to the backend service through WebSocket.

Example

The following example creates a connection to a local development backend service called [prscd](/prscd/introduction) at https://lo.yomo.dev:8443/v1, with both WebTransport and WebSocket supported.

import Presence from '@yomo/presence';
 
// create an instance.
const presencePromise = createPresence('https://lo.yomo.dev:8443/v1', {
  publicKey: process.env.NEXT_PUBLIC_PRESENCE_PUBLIC_KEY,
  id: 'user-client-id',
  debug: true,
});
 
presencePromise.then((presence) => {
  console.log('Presence: ', presence);
});
 
// or
// (async () => {
//   const presence = await presencePromise;
// })()
💡

lo.yomo.dev always points to 127.0.0.1, so you can use it for local development. Check out here for more examples.

presence.joinChannel(id, initState)

This method is used to join a channel and create a Channel instance. It takes in two parameters:

  • id: The id of the channel to join.
  • initState: Sync user's initial state to other peers.

This method tells other peers in this [Channel](/interface/channel) that this user is online with an initial state.

Example

The following example observes a channel named landing to get which page other peers are currently on:

const channel = presence.joinChannel('landing', { currentOn : '/docs/getting-stated' });