WebSocket establishes a persistent, full-duplex channel between your client and server. Unlike HTTP, where the client must initiate every exchange, WebSocket lets either side send messages at any time — making it ideal for chat, live updates, and collaborative tools. Elysia uses uWebSockets, the same engine Bun uses internally, so you get native performance with a familiar API.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/elysiajs/documentation/llms.txt
Use this file to discover all available pages before exploring further.
Basic setup
Call.ws() with a path and a handler object. The message callback receives the connected socket and the incoming message.
Message validation
Pass abody schema to validate incoming messages and a query schema for URL parameters. Validated data is available on ws.data.
| Field | Description |
|---|---|
message | Incoming WebSocket message payload |
query | URL query string parameters |
params | Path parameters |
header | Request headers at upgrade time |
cookie | Request cookies at upgrade time |
response | Value returned from a message handler |
Lifecycle handlers
Useopen, message, close, and drain to respond to connection events.
ServerWebSocket with a unique id string and a data property containing the typed request context.
Middleware hooks
The following standard Elysia middleware hooks run during the HTTP upgrade phase, before the connection is established:parse— parse the request bodytransform— transform context before validationbeforeHandle— validate or authorize the upgrade requesttransformMessage— transform the WebSocket message before validation
beforeHandle to reject unauthorized connections before they upgrade:
Configuration
Pass awebsocket object to the Elysia constructor to configure server-wide WebSocket behavior. These options extend Bun’s WebSocket configuration.
- perMessageDeflate
- maxPayloadLength
- idleTimeout
- backpressureLimit
- closeOnBackpressureLimit
Enable per-message compression for clients that support it. Disabled by default.
Handler type signatures
ws(endpoint, options)
ws(endpoint, options)
endpoint— the URL path to expose as a WebSocket handleroptions— handler callbacks and schema configuration
open(ws)
open(ws)
message(ws, message)
message(ws, message)
Message type is derived from schema.body.close(ws)
close(ws)
drain(ws, code, reason)
drain(ws, code, reason)