Using Awareness to determine the active users

The docs don’t go into the usage of awareness - I understand that this is because it’s unstable. But I’m trying to implement a feature where I show the active users editing a document.

This is what I’ve come up. I would love some feedback as to if this is the correct way to determine the active users, because it does seem to work.

Thank you for your help.

const awarenessProtocol = require('y-protocols/dist/awareness.cjs');
const awareness = new awarenessProtocol.Awareness(ydoc);

const provider = new WebrtcProvider(doc.id, ydoc, {
  signaling: [
    'wss://signaling.yjs.dev',
    'wss://y-webrtc-signaling-eu.herokuapp.com',
    'wss://y-webrtc-signaling-us.herokuapp.com',
  ],
  password: null,
  awareness,
  maxConns: 20 + Math.floor(Math.random() * 15),
  filterBcConns: true,
  peerOpts: {},
});

provider.awareness.on('change', ({ added, updated, removed }, origin) => {
  // logs an array of userIds
  console.log(Array.from(provider.awareness.states).map((state) => state[1].userId));
});

provider.awareness.setLocalState({ userId });

Hi @Kolby,

the Awareness protocol is stable and you can (and should) use it.

There is a getting started guide on the topic: https://docs.yjs.dev/getting-started/adding-awareness
And there is also internal documentation in case you want to port the Awareness-protocol to a custom provider: https://docs.yjs.dev/api/about-awareness

1 Like

Hold up… I’ve been struggling trying to parse through what’s in the repos, completely unaware there were docs…

Clicking on the “Documentation” link in the nav takes you to Github…

Thanks for the links I’m sure they will clear up a lot of my confusion :sweat_smile:

I’ve been building up the documentation in the past 5 weeks. It is still incomplete, but it does explain things better than the rather technical READMEs.

1 Like