Skip to main content

Handlers

Handlers are the core mechanism for processing WebSocket requests in WSX. They define how your server responds to different types of client interactions.

Handler Basics

Handler Function Signature

All handlers follow the same signature:

Registering Handlers

Register handlers using the on method:

Request Object

WSXRequest Properties

Accessing Request Data

Response Object

WSXResponse Properties

Basic Response

Handler Types

JSON Channel Handlers

Use wsx.onJson() to react to structured payloads that are broadcast or targeted to your server. JSON handlers receive a message envelope with id, channel, data, and optional metadata.
Register a catch-all handler with wsx.onJson(async (message) => { ... }) when you need to observe every channel.

Stream Handlers

Binary streams are ideal for audio, video, or other raw payloads. Register them with wsx.onStream() and work with the supplied Uint8Array data plus metadata.
Paired helpers like wsx.broadcastStream() and wsx.sendStreamToConnection() mirror the HTML response workflow but operate on binary buffers.

Named Handlers

Handle specific actions by name:

Event-Based Handlers

Handle by trigger type:

Catch-All Handler

Handle all unmatched requests:

Advanced Handler Patterns

Conditional Logic

Async Operations

Multiple Responses

Return arrays for multiple updates:

Handler Chaining

Middleware Pattern

Validation

Error Handling

Try-Catch Pattern

Graceful Degradation

Best Practices

  1. Always Return Responses: Handlers should return a response object
  2. Handle Errors: Use try-catch blocks for async operations
  3. Validate Input: Check request data before processing
  4. Use Session Data: Store connection-specific state in sessionData
  5. Keep Handlers Focused: Each handler should handle one specific action
  6. Log Appropriately: Log errors and important events

Next Steps