Skip to content
cabby

Node.js

Without a Rails-style RPC backend, run Cabby in standalone mode. Your app signs the names of the streams a visitor may read, the browser subscribes with that signed name, and your app broadcasts with a plain HTTP request. No server-side package is needed.

1. Run Cabby

Install Cabby, then start it in standalone mode:

cabby --norpc --noauth --secret=change-me --broadcast_key=change-me-too --broadcast_adapter=http

--noauth lets visitors connect without logging in; the signed stream names decide what each one can read. --broadcast_adapter=http takes broadcasts over HTTP only, so you don't need Redis.

2. Sign stream names on the server

CABBY_SECRET and CABBY_BROADCAST_KEY are your app's own variables. Start your app with them holding the same values you pass to --secret and --broadcast_key:

export CABBY_SECRET=change-me
export CABBY_BROADCAST_KEY=change-me-too

The helper uses ES modules. Set "type": "module" in your package.json:

npm pkg set type=module
// cabby.js
import { createHmac } from "node:crypto"

const SECRET = process.env.CABBY_SECRET // same value as --secret
const BROADCAST_KEY = process.env.CABBY_BROADCAST_KEY // same value as --broadcast_key
const BROADCAST_URL = process.env.CABBY_BROADCAST_URL ?? "http://localhost:8080/_broadcast"

export function signStream(name) {
  const encoded = Buffer.from(JSON.stringify(name)).toString("base64")
  const digest = createHmac("sha256", SECRET).update(encoded).digest("hex")
  return `${encoded}--${digest}`
}

export async function broadcast(stream, data) {
  const response = await fetch(BROADCAST_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json", Authorization: `Bearer ${BROADCAST_KEY}` },
    body: JSON.stringify({ stream, data: JSON.stringify(data) }),
  })
  if (!response.ok) throw new Error(`Cabby broadcast failed: ${response.status}`)
}

Pass the signed name to the page when you render it:

res.render("room", { signedStream: signStream(`room:${room.id}`) })

And print it into the page from your template (EJS here):

<script>window.signedStream = <%- JSON.stringify(signedStream) %></script>

3. Subscribe in the browser

Install the client and import it in the browser code you bundle:

npm install @anycable/web
import { createCable } from "@anycable/web"

const cable = createCable("ws://localhost:8080/cable")
const channel = cable.streamFromSigned(signedStream)

channel.on("message", (message) => console.log(message))

4. Broadcast

await broadcast(`room:${room.id}`, { text: "Hello" })