Skip to Content
HeronJS v4 is now available.
Versionv4WebSocketQuick Start

WebSockets

Native WebSocket extension for HeronJS on Node.js 24+. Browser WebSocket clients are supported. Socket.IO clients use a different protocol and are not supported.

import {Module} from '@heronjs/common'; import {HeronJS} from '@heronjs/core'; import {WebSocket, OnMessage, Payload} from '@heronjs/websocket'; import {z} from 'zod'; @WebSocket({namespace: '/chat'}) class Chat { @OnMessage({event: 'echo', schema: z.string()}) async echo(@Payload() value: string) { return value; } } @Module({websockets: [Chat]}) class App {} const app = await HeronJS.create({module: App}); app.add({ws: {}}); await app.listen({port: 3000}); // await app.close();
const socket = new WebSocket('ws://localhost:3000/ws/chat'); socket.onopen = () => socket.send(JSON.stringify({event: 'echo', data: 'hello'})); socket.onmessage = ({data}) => console.log(JSON.parse(data)); // { event: 'echo', data: 'hello' }

OnMessage({event, schema?, options: {replyTo?}}) receives an event and sends the handler’s result back to the originating connection. The reply uses the same event name by default; use @OnMessage({event: 'echo', options: {replyTo: 'reply'}}) for a separate response event. It combines ReceiveFrom and SendTo, which remain available separately. Use ReceiveFrom alone for handlers without an automatic reply. Do not stack OnMessage with another receive/reply decorator on the same method; duplicate registrations are rejected at startup. Replies are not broadcast to other clients.

Use Socket() for a peer with send({event, data}) and close(). SocketContext() provides connection ID, namespace, request, authenticated identity and abort signal. OnOpen(), OnClose() and OnError() receive the same decorated parameters; Payload() is { code, reason } on close and the Error on error. Handlers run sequentially per connection and return values, Promises, or RxJS Observables. Unary replies use the first emission.

Options on @WebSocket({namespace, options}): maxPayload (1 MiB), maxBufferedAmount (1 MiB), maxPendingMessages (256 active and waiting messages in each direction), heartbeatInterval (30000 ms), shutdownTimeout (5000 ms), allowedOrigins, authenticate({request}), and authorize({guard, context}). Set the shared URL prefix with app.add({ws: {wsPath: "/ws"}}). Endpoint settings in app.add() are rejected. Each gateway has independent limits and policy. Authentication returns an identity; a falsy identity rejects the upgrade. Class/method Guard metadata compares against that identity by default; custom authorize can evaluate application policies. Query strings do not change routing.

Compression, io and nonempty interceptor settings fail startup explicitly. Unknown events and handler/validation failures emit sanitized error events. Binary messages close with 1003, oversized frames with 1009, slow clients with 1013, and shutdown with 1001. Pending input and outbound buffering are bounded.

Validation and bounded queues

Use top-level schema on OnMessage or ReceiveFrom. The legacy options.schema is deprecated; providing both forms fails registration. Async parsing and transforms run after authorization. Validation failure sends {event: 'error', data: {code, issues}} and leaves the connection available for later messages. See Input validation.

Handlers are bound once per connection; authorization is still checked for each execution. maxPendingMessages bounds active and queued inbound messages and outbound writes, while maxBufferedAmount bounds buffered bytes. Observe the connection signal and await asynchronous work so cancellation and shutdown can finish cleanup.

Last updated on