WebSocket · In depth

BaseHandler

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

The simple mental model

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 it fits

When should I use it?

Create a small handler for each message type that deserves its own validation, authorization, rate policy, and behavior.

A practical API pattern

Follow the example

This pattern explains the named API. Application classes, credentials, and assets may need to be supplied; use a complete recipe for a runnable starting point.

Read this article as Markdown

JavaScript
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 })
  }
}
  1. 1

    The handler name declares the message type it accepts.

  2. 2

    SocketRoute performs dispatch before onMessage runs.

  3. 3

    The handler validates the payload, changes authoritative state, and sends or broadcasts the result.

Surface area

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).