How to send Yjs document through normal Websocket?

Every example I have found uses y-websocket to send the doc using WebsocketProvider. I’m currently using uWebsocket.js for the server and plain Websocket for client side. The normal Websocket doesn’t seem to have a provider and can’t find anything for uWebsocket either.

All help is greatly appreciated!

On the client, you can use the WebsocketPolyfill option to sub out the built-in WebSocket object, though you might be able to use the y-websocket client as-is. The websocket connection logic for YJS is at lib0/websocket.js at main · dmonad/lib0 · GitHub in case that is useful.

On the server, you would probably need to fork y-websocket and replace the websocket calls with uWebsocket.js equivalents.

I don’t think there is a more plug-and-play solution unfortunately.

I didn’t quite understand this. Do you mean client-side or server-side? The y-websocket provider does use the built-in WebSocket object.

1 Like

Thanks for the reply and the help!

import * as Y from 'yjs'
import { WebsocketProvider } from 'y-websocket'

const doc = new Y.Doc()
const wsProvider = new WebsocketProvider('ws://localhost:1234', 'my-roomname', doc)

wsProvider.on('status', event => {
  console.log(event.status) // logs "connected" or "disconnected"
})

This is the code snippet I was writing about. I assume the WebsocketProvider is used to send it to the server which can broadcast the Y.doc to the other clients? So I’m wondering how to send the Y.doc to the other clients without using y-websocket and only uWebsocket.js

Thanks!

I think you would need to fork y-websocket and replace the websocket calls on the server with uWebsockets.js. That’s assuming that uWebsockets.js id a drop-in replacement which may not be the case.

It would be simple if what was needed was just to send the Y.Doc in a single request. However, collaborative editing over websocket involves connecting to the server, retrying failed connection attempts, sending pings to keep the connection open, subscribing to updates, handling multiple tabs, sharing awareness state, gracefully closing the connection, etc. y-websocket does all of that, so you probably don’t want to bypass it. You just want it to use a different networking implementation.

1 Like