Skip to Content
HeronJS 3.6 with fully support Typescript 6 is released 🎉
WebSocketOverview

WebSocket controllers handle real-time communication in HeronJS. They are built on top of socket.io  and allow you to organize events by namespace, receive messages from clients, and send responses through different reply strategies.

Create a WebSocket controller

Create a file for your WebSocket controller, for example:

  • src/ws/todo.ws.ts
import { WebSocket } from '@heronjs/common'; @WebSocket('todows') export class TodoWs {}

This creates a WebSocket namespace for todows.

Create an event handler

Use @ReceiveFrom() to listen for an incoming event from the client.

@ReceiveFrom('todo:create', ReplyMethod.ACKNOWLEDGEMENT) public async createTodo(message: Message<Any>): Promise<Any> { return message; }

In this example:

  • todo:create is the event name the client sends.
  • ReplyMethod.ACKNOWLEDGEMENT replies directly through the socket acknowledgment callback.

Event decorators

DecoratorDescriptionNote
@ReceiveFrom(name, replyMethod)Receives an event from the client and processes it.
@Guard(...)Applies authorization rules to the event handler.
@SendTo(event, namespace)Sends the result to another event or namespace.

Reply methods

Reply methodDescriptionNote
ACKNOWLEDGEMENTResponds directly through the client callback.Also known as an ACK packet.
BROADCASTBroadcasts the result to all clients across instances.
EVENTSends the result back through another event name.Example: todo:create:result
LOCALBroadcasts the result to clients on the same instance only.
MANUALLets you respond manually using the Socket object.The last argument is usually a Socket.
VOLATILESends a best-effort response without guaranteeing delivery.Similar to UDP behavior.

Register WebSocket controllers

Register the controller in the module websockets array.

@Module({ websockets: [TodoWs], }) export class AppModule {}

Configure the WebSocket server

In HeronJS, the WebSocket server runs as a subserver. Configure it through the subServer.ws option when starting the app.

const main = async () => { const app = await HeronJS.create({ module: AppModule }); await app.listen({ port: 3000, options: { cors: { origin: '*', preflightContinue: false, methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', }, globalError: GlobalApiErrorInterceptor, }, subServer: { ws: { io: {}, compression: {}, wsPath: '/ws', }, }, }); };
ArgumentDescriptionNote
iosocket.io server configuration.See socket.io  for available options.
compressionConfigures payload compression.
wsPathSets the global WebSocket server path.
Last updated on