BaseHandler
Documentation for Redweb 0.13.3. Install that exact version when following these examples.
Abstract message handler. Provide a name in the constructor; clients send { type: name, ... } to target JSON messages, while binary frames can be accepted and handled as raw Buffer payloads.
Explain it like I’m five
BaseHandler is a labeled mailbox. A message with the matching type goes directly into that mailbox, so your code does not need a switch statement.
When should I use it?
Create a small handler for each message type that deserves its own validation, authorization, rate policy, and behavior.
Follow the example
This API pattern illustrates the named surface; it may require application-owned classes, credentials, or assets. Start from a complete recipe for a runnable application.
const { BaseHandler } = require('redweb')
class UploadHandler extends BaseHandler {
constructor() { super('upload') }
onMessage(socket, message) {
socket.sendJson({ type: 'upload:control', action: message.action })
}
acceptsBinary(socket, buffer) {
return buffer.length > 0
}
onBinaryMessage(socket, buffer) {
socket.sendJson({ type: 'upload:chunk', bytes: buffer.length })
}
}- The handler name declares the message type it accepts.
- SocketRoute performs dispatch before onMessage runs.
- The handler validates the payload, changes authoritative state, and sends or broadcasts the result.
Methods and members
constructor(name)
Stores the handler name used by incoming messages.
handleMessage(socket, message)
Calls onMessage; override only if you need pre/post handling logic.
onMessage(socket, message)
Required; implement your message processing here. Throwing will close the socket with an error.
acceptsBinary(socket, buffer)
Optional selector used by SocketRoute to choose a handler for binary frames. Return true when this handler should receive the Buffer.
handleBinaryMessage(socket, buffer)
Calls onBinaryMessage. If onBinaryMessage is not implemented, Redweb sends a "Binary messages are not supported by this handler" error.
onBinaryMessage(socket, buffer)
Optional; override for normal binary-message handling. The second argument is the raw Buffer payload.
onInitialContact(socket)
Optional hook for first-touch logic (not used by default route).
What should I watch for?
Do not add a second message.action dispatcher inside one handler. That hides protocol operations and defeats type-based routing.