JSON routing, broadcast, and binary frames
Documentation for Redweb 0.13.3. Install that exact version when following these examples.
Text messages select a handler by type. Binary frames stay as Buffer values and can be accepted by the handler that understands them.
This pattern demonstrates one API area. Application-specific names, credentials, assets, and policies may need to be supplied. Complete starter recipes include all required application files.
const { BaseHandler, SocketRoute } = require('redweb')
class ChatHandler extends BaseHandler {
constructor() { super('chat') }
onMessage(socket, message) {
socket.broadcast({ type: 'chat', text: message.text })
}
}
class SnapshotHandler extends BaseHandler {
constructor() { super('snapshot') }
onMessage() {}
acceptsBinary(_socket, buffer) { return buffer.length > 0 }
onBinaryMessage(socket, buffer) {
socket.sendJson({ type: 'snapshot:received', bytes: buffer.length })
}
}
class RealtimeRoute extends SocketRoute {
constructor() {
super({
path: '/realtime',
handlers: [ChatHandler, SnapshotHandler],
websocketOptions: { maxPayload: 64 * 1024 },
})
}
}Notes and boundaries
- sendJson and broadcast share the same outbound policy.
- acceptsBinary can select among multiple binary handlers.
- Async handler failures become safe client errors.