Using y-websocket on the client with the Node WebSocket library ws

I have copied the Quill example and updated the WebSocket URL to connect with a node WebSocket server that simply broadcasts any messages it receives to all other clients connected to the WebSocket server.

If I open my client in Chrome & Firefox and start typing, the text and cursor are synchronised. I wasn’t expecting this to happen as I thought I also needed to run y-websockets on the server.

Given that on the surface this appears to be a solution, what features am I missing by not using y-websockets on the server, and what other potential issues may appear?

That’s a very cool feature of Yjs :slight_smile:

However, this implementation is not “ideal”.

Every time a client connects, all existing clients will propagate all content to all users. Yjs will be able to filter-out duplicate information. But there is network overhead.

Usually, you want a server to initialize the content. You shouldn’t let clients initialize content, because that will likely lead to duplication.

y-webrtc achieves the same thing without involving a server for broadcasting all messages. Also, it ensures that not all data is broadcasted to all clients whenever a user connects.

1 Like

Yes I am trying to use our existing websocket service to broadcast the messages to all other connected clients instead of running a separate y-websocket server.

Is it possible to initialize content in the browser of the first connecting client? Any subsequent connecting clients will receive the content when they connect to the websocket.

I see the advantages, but I advise against it. This is the leading cause of data loss for Yjs users.

There is no reliable algorithm for selecting a client to initialize content. The first client might be unresponsive… until it isn’t… and this might lead to loss of data / users overwriting each others content.

There is no “I can fix it”. It really can’t be done it praxis (I’ve never seen it done).

Also, you might have clients that disconnect for a time. When they reconnect, they might join a room with existing content.

Content should only be initialized once.

1 Like

Initialized once in the entire history of the document? i.e. it is initialized on the server, stored somewhere e.g. database, and then that document is the source of truth for all future connecting clients?

Yes, that is my recommendation. It will save you a lot of trouble and avoid content duplication / overwriting content when you initialize content twice. Also, it enables you to use y-indexeddb to cache documents on the client-side.