Skip to main content

Server Handlers

Handlers are the core of WSX server functionality. They process incoming WebSocket requests from clients and return responses that update the browser DOM.

Basic Handler Setup

Simple Handler

Default Handler

Handler Function Signature

Request Object

Connection Object

Response Object

Handler Patterns

Form Handling

Data Fetching

CRUD Operations

Advanced Handler Features

Session Management

Multiple Responses

Conditional Logic

Error Handling

Try-Catch Pattern

Validation

Graceful Degradation

Handler Middleware

Authentication Middleware

Validation Middleware

Logging Middleware

Performance Optimization

Caching

Database Connection Pooling

Testing Handlers

Unit Tests

Integration Tests

JSON Handlers

In addition to HTML responses, WSX servers can subscribe to JSON message channels. JSON handlers receive a structured payload plus optional metadata and can broadcast messages to other clients.
Every JSON message includes:
  • id: Unique identifier (auto-generated when omitted)
  • channel: Logical name for routing
  • data: Any JSON-serializable payload
  • metadata: Optional contextual information
Use the helper methods to target specific audiences:

Stream Handlers

Stream handlers process binary payloads such as audio, video, or sensor readings. Messages arrive with metadata describing the stream plus a Uint8Array payload.
Stream helpers mirror the HTML and JSON APIs:
Incoming metadata is optional, so defensively check for fields before using them. Streams are delivered as Uint8Array views—convert to Buffer or copy to an ArrayBuffer when necessary.

Best Practices

  1. Always Return Responses: Handlers should return a response object
  2. Handle Errors Gracefully: Use try-catch blocks and provide user-friendly error messages
  3. Validate Input: Check and validate all incoming data
  4. Use Session Data: Store connection-specific state in sessionData
  5. Keep Handlers Focused: Each handler should handle one specific action
  6. Implement Security: Check permissions and authenticate users
  7. Log Appropriately: Log errors and important events for debugging
  8. Test Thoroughly: Write unit and integration tests for handlers

Next Steps