Skip to Content
HeronJS v4 is now available.
4.0.0WebSocketQuick Start

WebSocket Quick Start

@heronjs/websocket provides native WebSocket connections on Node.js 24 or later. Browser WebSocket clients are supported. Socket.IO clients use a different protocol and are not supported.

Define a handler

import 'reflect-metadata'; import {Module} from '@heronjs/common'; import {HeronJS} from '@heronjs/core'; import {WebSocket, ReceiveFrom, SendTo, Payload} from '@heronjs/websocket'; import {z} from 'zod'; @WebSocket('/chat') class Chat { @ReceiveFrom('echo', {schema: z.string()}) @SendTo('reply') 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();

Connect a client

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: 'reply', data: 'hello' }

Handler context and lifecycle

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.

Connection options

Options under ws: wsPath (/ws), maxPayload (1 MiB), maxBufferedAmount (1 MiB), heartbeatInterval (30000 ms), shutdownTimeout (5000 ms), allowedOrigins, authenticate(request), and authorize(guard, context). 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.


Based on 4.0.0 release source  (4.0.0).

Last updated on