Skip to content

Broadcasting ​

Introduction ​

Broadcasting pushes server-side events to connected browsers so a page can update without polling. An order ships, a message is posted, a job finishes: you announce it on a named channel, and every client listening to that channel receives it.

@plinthjs/broadcasting is the server half of that arrangement. It defines which events broadcast, which channels they go to, who is allowed to listen on private channels, and which driver carries the message out. The delivery half, a WebSocket server that clients connect to, is WebSockets.

bash
pnpm add @plinthjs/broadcasting

Broadcasting an event ​

An event that broadcasts implements ShouldBroadcast. Its only required method is broadcastOn(), which returns one channel or an array of channels. Two optional methods shape the message: broadcastAs() sets the event name (the class name is used when omitted) and broadcastWith() sets the payload (an empty object when omitted).

ts
import {
  broadcast,
  BroadcastManager,
  privateChannel,
  type ShouldBroadcast,
} from '@plinthjs/broadcasting'

class OrderShipped implements ShouldBroadcast {
  constructor(private readonly order: { id: number; userId: number }) {}

  broadcastOn() {
    return privateChannel(`orders.${this.order.userId}`)
  }

  broadcastAs() {
    return 'order.shipped'
  }

  broadcastWith() {
    return { id: this.order.id }
  }
}

const manager = new BroadcastManager({ default: 'log', logSink: (line) => console.log(line) })

await broadcast(new OrderShipped({ id: 7, userId: 1 }), manager.driver())
// logs: Broadcasting [order.shipped] on channels [private-orders.1] with payload {"id":7}

broadcast(event, broadcaster?) resolves the event's channels, name and payload, then hands them to the broadcaster. With no broadcaster it uses a NullBroadcaster, which discards everything. The three helpers it relies on are exported if you need them: eventChannels(event), eventName(event) and eventPayload(event).

ts
eventName(new OrderShipped({ id: 7, userId: 1 })) // => 'order.shipped'

An event without broadcastAs is announced under its class name, so a class Plain is broadcast as Plain.

Broadcasting immediately ​

When you give broadcasting a queue, plain events are queued and events marked with broadcastNow(event) skip it. Without a queue everything is sent inline. A queue is any object with push(job), where the job has the wire event name and a handle() that publishes. Pass it as the third argument of broadcast(), or as the queue option of the BroadcastManager and call manager.broadcast(event, driverName?).

ts
import { BroadcastManager, broadcastNow, isShouldBroadcastNow } from '@plinthjs/broadcasting'
import type { BroadcastJob } from '@plinthjs/broadcasting'

const jobs: BroadcastJob[] = []
const manager = new BroadcastManager({
  default: 'array',
  queue: { push: (job) => void jobs.push(job) },
})

await manager.broadcast(new OrderShipped({ id: 7, userId: 1 })) // queued: jobs.length => 1, nothing sent yet
await jobs[0].handle() // the worker sends it

await manager.broadcast(broadcastNow(new OrderShipped({ id: 8, userId: 1 }))) // sent immediately, bypasses the queue
isShouldBroadcastNow(broadcastNow(new OrderShipped({ id: 9, userId: 1 }))) // => true

In a real application push wraps the job in a queue Job whose handle() calls job.handle().

isShouldBroadcast(value) reports whether any value has a broadcastOn method.

Channels ​

There are three kinds of channel, differing only in their name prefix and in who may join.

ts
import { channel, Channel, presenceChannel, privateChannel } from '@plinthjs/broadcasting'

new Channel('news').name() // => 'news'              public
privateChannel('orders.1').name() // => 'private-orders.1'     authorized listeners only
presenceChannel('chat.5').name() // => 'presence-chat.5'      authorized, with a member list

channel('orders.1', 'private').name() // => 'private-orders.1'
privateChannel('orders.1').base() // => 'orders.1'
  • A public channel has no prefix, and anyone may listen.
  • A private channel is prefixed private-. Clients must prove they are allowed to listen.
  • A presence channel is prefixed presence-. It is private, and also identifies who is joined.

An event can broadcast to several channels at once by returning an array:

ts
broadcastOn() {
  return [channel('orders'), privateChannel(`orders.${this.order.userId}`)]
}

Authorizing channels ​

You decide who may listen to a private or presence channel by registering a callback against a channel pattern in a ChannelRegistry. A pattern can contain {name} placeholders, each matching one dot-separated segment and passed to your callback as a parameter.

ts
import { ChannelRegistry } from '@plinthjs/broadcasting'

const channels = new ChannelRegistry()
  .channel('orders.{userId}', (user, { userId }) => (user as { id: number }).id === Number(userId))
  .channel('chat.{roomId}', (user) => ({ id: (user as { id: number }).id, name: 'Ada' }))

channels.authorize('private-orders.1', { id: 1 }) // => true
channels.authorize('private-orders.2', { id: 1 }) // => null (denied)
channels.authorize('presence-chat.5', { id: 1 }) // => { id: 1, name: 'Ada' }
channels.authorize('private-unknown', { id: 1 }) // => null (no pattern matches)
channels.has('private-orders.9') // => true

The private- and presence- prefixes are stripped before matching, so you register orders.{userId}, not private-orders.{userId}. A callback that returns true allows the user. One that returns false, null or undefined denies, and authorize then returns null. For a presence channel, return an object describing the member instead of true; authorize returns it as-is.

The authorization route ​

Browsers do not talk to the registry directly. A client library asks your HTTP application to authorize a channel, and your application answers with a signature the WebSocket server can check. The request is a POST to a path you choose (the conventional one is /broadcasting/auth) carrying the client's socket_id and the channel_name.

Write one function that turns that request into a response body, and call it from a route handler (see Routing) after you have identified the signed-in user (see Authentication).

ts
import { createHmac } from 'node:crypto'

const APP_KEY = 'app-key'
const APP_SECRET = process.env.BROADCAST_SECRET ?? 'change-me'

export function authorizeChannel(user: { id: number }, socketId: string, channelName: string) {
  const result = channels.authorize(channelName, user)
  if (result === null) return null // respond with 403

  const signed =
    typeof result === 'object' && channelName.startsWith('presence-')
      ? `${socketId}:${channelName}:${JSON.stringify({ user_id: user.id, user_info: result })}`
      : `${socketId}:${channelName}`

  const auth = `${APP_KEY}:${createHmac('sha256', APP_SECRET).update(signed).digest('hex')}`

  return typeof result === 'object' && channelName.startsWith('presence-')
    ? { auth, channel_data: JSON.stringify({ user_id: user.id, user_info: result }) }
    : { auth }
}

The signature scheme here is the one Pusher-compatible clients expect. The WebSocket server does not verify it for you; you check it in its authorizeSubscription hook, as shown in WebSockets.

Drivers and the broadcast manager ​

A driver is anything with a broadcast(channels, event, payload) method that takes an array of Channel objects. BroadcastManager resolves named drivers and caches them. Three are built in.

DriverWhat it does
nullPublishes nothing. This is the default.
logWrites one line per broadcast to a sink. Requires the logSink option.
arrayA BroadcastFake that records broadcasts so you can assert on them.
ts
const manager = new BroadcastManager({ default: 'log', logSink: console.log })

manager.getDefaultDriver() // => 'log'
manager.driver() // the default, cached
manager.driver('array') // a BroadcastFake
manager.connection('null') // alias of driver()

manager.driver('missing') // throws: Broadcast driver [missing] is not defined.
new BroadcastManager().driver('log') // throws: Broadcast driver [log] requires a `logSink` option.

Add your own driver with the drivers option or extend. A factory returns a broadcaster.

ts
manager.extend('ws', () => new WebSocketBroadcaster(server)) // see below

Delivering through the WebSocket server ​

WebSocketBroadcaster is the driver that bridges broadcasting to the WebSocket server. It publishes each channel under its wire name with the server's broadcast(channelName, event, data). It only needs that one method, so this package does not depend on the websockets package.

ts
import { broadcast, BroadcastManager, WebSocketBroadcaster } from '@plinthjs/broadcasting'
import { WebSocketServer } from '@plinthjs/websockets'

const server = new WebSocketServer()

const manager = new BroadcastManager({
  default: 'ws',
  drivers: { ws: () => new WebSocketBroadcaster(server) },
})

await broadcast(new OrderShipped({ id: 7, userId: 1 }), manager.driver())

Every client subscribed to private-orders.1 now receives { event: 'order.shipped', channel: 'private-orders.1', data: { id: 7 } }. See WebSockets for the server, and Notifications for the notification broadcast channel that sits on top of a driver like this.

Testing broadcasts ​

The array driver, a BroadcastFake, records every broadcast. Its assertions throw when they fail and return the fake on success, so they chain.

ts
import { BroadcastFake, broadcast } from '@plinthjs/broadcasting'

const fake = new BroadcastFake()
await broadcast(new OrderShipped({ id: 7, userId: 1 }), fake)

fake
  .assertBroadcasted('order.shipped') // by event name
  .assertBroadcasted((b) => b.payload['id'] === 7) // or by predicate
  .assertBroadcastedOn('private-orders.1')
  .assertBroadcastedOn('private-orders.1', 'order.shipped')
  .assertNotBroadcasted('other.event')

fake.broadcasts()
// => [{ channels: ['private-orders.1'], event: 'order.shipped', payload: { id: 7 } }]

assertNothingBroadcasted() checks that nothing was sent. ArrayBroadcaster is another name for BroadcastFake.

Released under the MIT License.