Deploying server with y-websocket

How do I deploy express server with y-websocket? I am using the same configuration I use on local machine. I tried deploying to Railway, but it seems that I can’t connect to it.

  "start": "node build/index.js & y-websocket"

I think this has to do something with the HOST option in the y-websocket cli. If so, what should be the value of the HOST option?

Can I directly use npx y-websocket on server? @dmonad

Or is there any example repo for using y-websocket with express server?

Got it working with express-ws, but is this the correct way?

import * as dotenv from 'dotenv'

import express from 'express'
import expressWs from 'express-ws'
// @ts-expect-error import directly from dist folder
import { setupWSConnection } from '../../node_modules/y-websocket/bin/utils.js'

const { app } = expressWs(express())
const port = process.env.PORT || 3333


app.get('/', (_, res) => {
  res.json({ hello: 'world' })
})'/collaboration/:document', (ws, req) => {
  setupWSConnection(ws, req, { docName: req.params.document })

app.listen(port, () => {
  console.log(`express server started on ${port}`)

See the code here; I think you should let host to be if you want to deploy to the remote server

1 Like

Yes. You just have to make sure the HOST and PORT are correct for your web server setup.

Looks fine to me. You can also copy server.js and build your own server based on that. It involves calling setupWSConnection when the websocket connects:

wss.on('connection', setupWSConnection)

More advanced setups are possible, such as only calling setupWSConnection after receiving a message containing an authentication token, as used in y-websocket-auth: y-websocket-auth/server.js at 11f3856059afbe83c136769a5f696cab11e48951 · raineorshine/y-websocket-auth · GitHub.


@wwyomwzp just to highlight that authN bit that Raine pointed out is the important and slightly tricky bit to get your head around if you aren’t familiar with websockets. There’s no built in authN/Z support for WS. It’s great that Raine has shared y-websocket-auth.