gotchatypescriptModerate
Yjs Provider Must Be Connected Before Awareness Updates Are Shared
Viewed 0 times
yjsawarenesspresencecursor sharingwebsocket providery-websocketcollaborative editing
Problem
Cursor positions and user presence set via yjs awareness appear locally but are never visible to other connected peers. The awareness state is updated in code but nothing propagates.
Solution
Ensure the provider is created and connected before setting awareness state. WebsocketProvider syncs awareness automatically once the connection is established. Set local state after provider construction.
import * as Y from 'yjs';
import { WebsocketProvider } from 'y-websocket';
const doc = new Y.Doc();
const provider = new WebsocketProvider('wss://your-server', 'room-name', doc);
// Wait for connection before setting awareness
provider.on('status', ({ status }: { status: string }) => {
if (status === 'connected') {
provider.awareness.setLocalStateField('user', {
name: currentUser.name,
color: currentUser.color,
cursor: null
});
}
});
// Listen for remote awareness changes
provider.awareness.on('change', () => {
const states = Array.from(provider.awareness.getStates().values());
renderPresence(states);
});Why
Awareness state is transported over the same WebSocket connection as document updates. If the provider is not yet connected, setLocalState calls queue locally but the server never receives them until the socket opens.
Gotchas
- Awareness state is ephemeral — it does not persist in the Y.Doc and is lost on disconnect.
- Each client gets a unique clientID — use this to identify cursors, not a user identifier.
- setLocalStateField merges into the existing local state; setLocalState replaces it entirely.
- When a peer disconnects, their awareness entry is removed after a configurable timeout.
Revisions (0)
No revisions yet.