@websocket decorator defines a WebSocket API that opens a bidirectional message channel between client and server. Unlike @stream (SSE-only), it can also handle events sent by the client (inEvents) and broadcast messages to other connections in the same namespace/room.
Basic Usage
Since 0.12, room/user mutations and runtime publishes return a
Promise<void>. await them so the presence store has seen the change before your next step. These promises never reject, so calling them without await is also safe.Options
outEvents
Defines server → client event types using a Zod schema. Required option@websocket route’s outEvents in the runtime’s route table, keyed by the route path. A runtime publish validates and encodes the payload once per route that declares the event, and each connection receives the frame for its own route. Routes in the same namespace may declare different schemas for the same event name; connections on a route that does not declare the event are skipped.
inEvents
Defines client → server event types using a Zod schema. Required optionInbound messages are validated against
inEvents via the envelope contract and never reach handlers when they fail. An event not declared in the schema closes the connection with 1008 Policy Violation; a payload that fails validation closes it with 1007 Invalid Frame Payload Data.path
WebSocket endpoint path. Default:/{modelName}/{methodName} (camelCase)
namespace
A logical group that scopes routing/broadcast inside the same server.Sonamu.websocketRuntime.publishToRoom(roomId, event, data, namespace) only delivers to connections in the same namespace.
Default: "default"
heartbeat
Heartbeat (ping) interval in milliseconds. Default:30000 (30 seconds)
guards
Restricts who can connect.guardHandler throws a 4xx Sonamu exception such as UnauthorizedException, the connection closes with 1008 Policy Violation; any other error closes it with 1011.
description
Adds a description for the WebSocket API.resourceName
Specifies the resource name for the generated service file.WebSocketContext
A@websocket-decorated method receives WebSocketContext<TOut, TIn> as its last argument.
ctx.ws.publish
Sends an event to this connection only. It is synchronous and throws when the event is not declared inoutEvents or the payload fails validation.
ctx.ws.onMessage
Handles events sent by the client.ctx.ws.onClose
Runs cleanup when the connection closes. The connection is already removed from the registry, including all of its rooms and its user binding, before the callbacks run, so you do not need to callleave here.
ctx.ws.waitForClose
Keeps the handler alive until the connection closes. WebSocket methods typicallyawait this promise to wrap up.
ctx.ws.join / ctx.ws.leave
Joins or leaves a room, which is the broadcast unit. Both returnPromise<void>.
ctx.ws.setUserId / ctx.ws.clearUserId
Attaches a user identifier to the connection so it can be targeted bypublishToUser. Both return Promise<void>.
setUserId(1) does not receive publishToUser("1", ...). Use the same type when binding and publishing.
Mutation semantics
join, leave, setUserId, and clearUserId update the node-local registry synchronously at call time, so a publish issued right after ctx.ws.join("r") (even without await) already reaches this connection. The returned promise settles after the presence store call for the change resolves or fails. Store calls for one connection run in call order.
The promises never reject. If the presence store fails, the node-local state stays updated, later mutations for the connection still run in order, and the failure is reported as the ws.registry.mutation.failed telemetry event. Calling a mutation on a connection that has already closed is ignored and emits ws.registry.mutation.skipped.
Broadcast
From outside the handler you can also push messages to other connections viaSonamu.websocketRuntime.
These methods never reject:
- If the event is unknown to every route, or the payload fails a route’s
outEventsschema, nothing is sent to that route’s connections, no connection is closed, and the runtime emitsws.publish.rejectedtelemetry. Routes whose schema accepts the payload still receive it. - If routing or the cluster bus fails, local delivery still happens, remote delivery is skipped, and the failure is reported through
ws.fanout.*/ws.cluster.*telemetry.
Reading presence
Read APIs live onSonamu.websocketRuntime.registry.
Node-local reads return snapshot copies; changing a returned object (including its
rooms set) does not affect the registry.
getRoomMembers stays node-local, so it cannot see members on other nodes. To evict a specific user from a room, use leaveUser, not getRoomMembers + leave.
getRoomMemberCount asks the presence store for the active member count across all nodes and never rejects. When the store call throws or rejects, it returns this node’s count with partial: true and emits ws.registry.read.failed telemetry. The runtime does not put its own timeout on the call: the Redis adapter rejects when a call exceeds its commandDeadlineMs, which produces the fallback, but a custom store whose call never settles leaves the returned promise pending.
Removing a user from a room
leaveUser removes a user from a room on every live node. It is available on both Sonamu.websocketRuntime and Sonamu.websocketRuntime.registry.
leaveUser(userId: WebSocketUserId, roomId: WebSocketRoomId, namespace?: string): Promise<WebSocketLeaveUserResult>.
- It removes every session bound to (
namespace,userId) fromroomId. An empty or omittednamespacemeans all namespaces.userIdmatches by type (1and"1"are different). - It does not close connections. The same session’s other rooms and other users are untouched.
- It is idempotent: no matching session is still a success.
- Local sessions are removed synchronously before any remote work, so events published from this node after the call starts are not delivered to them. The returned promise waits for the local presence store mutations and the remote control publish.
- It never rejects. Failures are reported as
partial: trueplus telemetry, likegetRoomMemberCount.
getLiveNodeIds(). Otherwise the runtime uses resolveRoute(WebSocketAudience.user(userId, namespace), nodeId).remoteNodeIds. If that lookup or the publish fails, the remote part is skipped and the result is partial: true. targetNodeCount is the number of nodes attempted. When the store lacks getLiveNodeIds, the resolveRoute fallback targets only nodes with ACTIVE sessions of that user, so a registered-but-not-activated remote session is not removed.
Telemetry:
The existing
ws.cluster.envelope.ignored reasons selfSource and targetMismatch also apply to control envelopes.
Limits
- At-most-once delivery. Cluster messages use pub/sub.
partial: falsemeans the publish succeeded, not that remote nodes applied it. A node whose subscription is down at that moment misses the leave. - Concurrent publishes. Events published at the same time by another node B can reach node C before the leave is applied.
- Join race. If the app checks permission and then calls
joinwhile aleaveUserfrom another node is applied in between, the join is applied last and the user stays in the room.
leaveUser followed by publishToRoom from node A applies in that order on node C.
Recommended pattern: commit the membership change to the database first, then call leaveUser. On subscribe, run setUserId → permission check → join → permission re-check → leave on failure. Optionally re-check periodically.
Runtime configuration
Configure the runtime withserver.websocket in sonamu.config.ts. A single node works with the defaults.
The random suffix in the default
nodeId keeps a restarted container with the same hostname and PID from inheriting the previous node’s state. If presenceStore or clusterBus exposes a nodeId that differs from the runtime’s nodeId, runtime creation throws.
On shutdown, the runtime closes local connections, waits up to drainTimeoutMs for queued store mutations and publishes, then calls presenceStore.shutdown() (if defined) and clusterBus.shutdown().
Inbound frame size limit
server.plugins.ws.options.maxPayload (bytes) sets the maximum size of a single client frame. The default is 64 KiB (65536). A frame over the limit closes the connection with close code 1009 (Message Too Big). Raise it explicitly only when you need larger messages.
ws.message.buffer.dropped telemetry is recorded. If a guard rejects the connection, the held frames are discarded without being parsed.
Custom presence store
Every method may return a value or a promise (MaybePromise<T> = T | Promise<T>). A synchronous throw is treated like a rejection.
- Each node calls the store only for its own sessions. Calls for one session are issued in call order, each after the previous one settles;
unregisteralways comes afterregister. resolveRoutesplits an audience into the caller’s local session IDs and deduplicated remote node IDs, excluding inactive sessions.connectionsaudiences are routed from the node ID embedded in each session ID without calling the store.getRoomMemberCountcounts active members across the cluster.getLiveNodeIdsis optional and returns every live node ID.leaveUsertargets those nodes; without it, the runtime falls back toresolveRoutefor the user audience.- User IDs must match by type (
1and"1"are different). - Return copies from read methods; callers must not be able to mutate store state.
- Bound your own calls. The runtime treats a throw or rejection as a failure but applies no timeout, so a call that never settles keeps that session’s later mutations, remote publish routing, and
getRoomMemberCountwaiting. Shutdown stops waiting for pending mutations and publishes afterdrainTimeoutMs.
InMemoryWebSocketPresenceStore is the default. Several runtimes in one process can share one instance as a cluster replica, which is useful in tests.
Custom cluster bus
- Accept the whole union and forward
kindunchanged. Receivers treat an envelope withoutkindaspublish. - An envelope with an unknown
kindor a schema failure is dropped, and the runtime emitsws.cluster.envelope.rejected. The Redis adapter reports it through the optionalsubscribe(handler, { onRejected })callback. - Deliver each envelope only to the nodes in
targetNodeIds. - The envelope carries frames already validated and encoded by the origin node. The receiving node resolves the audience from its own memory and sends each connection the frame for its route byte for byte, without re-validating. A
z.date()field therefore arrives as the same ISO string on every node. subscribemay return the unsubscribe function directly or through a promise. The runtime calls it once on shutdown. Ifsubscribefails, the runtime keeps working in local-only mode and reports it through telemetry.- Connections registered without a route key (for example, through
registerConnectionon a manually created runtime) receive local publishes only.
Multi-node with Redis
@sonamu-kit/websocket-redis-adapter provides a Redis presence store and cluster bus. It requires sonamu 0.13.9 or later (adapter 0.13.9) and the redis (node-redis) package ^6 as a peer dependency.
server.websocket. The adapter’s nodeId, presenceStore, and clusterBus then share one node ID, so the runtime’s node ID check passes.
redis option accepts one of:
RedisClientOptions: the adapter creates and owns the clients.- An existing
RedisClient: you own it. The adapter only creates and closes aduplicate()for pub/sub. - An existing
RedisSentinel: you own it. The adapter subscribes on the Sentinel instance, so pub/sub follows failovers.
connect() on a client or Sentinel you pass in, and attach your own error listener to it.
The package also exports
REDIS_WEBSOCKET_ADAPTER_DEFAULTS (the default values above) and RedisWebSocketDeadlineError. presenceStore.getStatus() returns { ready, rebuildPending }.
Failure handling:
- A pending rebuild rewrites all of the node’s presence keys from memory at the first of: a standalone client
ready(reconnect), a SentinelMASTER_CHANGE, or the next successful heartbeat. - Each heartbeat also checks that the node’s presence keys still exist. If Redis lost a key that memory says must exist (for example through eviction or
FLUSHDB), the adapter schedules a rebuild even though no command failed. getRoomMemberCountcounts this node’s members from memory and only other nodes’ members from Redis, so the count stays correct while this node’s keys are being rebuilt.- With a Sentinel, every new
MASTER_CHANGEschedules a rebuild, because a failover can lose recent writes. Repeated events for the same master are ignored, and bursts are debounced into one rebuild. After a failover,EVALSHAthat fails withNOSCRIPTis retried once afterSCRIPT LOAD. - If the cluster bus subscription does not complete in time,
subscriberejects and the runtime reportsws.cluster.subscribe.failed. The adapter keeps the subscription request and completes it when the connection becomes ready, so this node starts receiving remote publishes again.
Migrating to 0.13.9
leaveUser:registry.leaveUser(userId, roomId, namespace?)andruntime.leaveUser(...)remove a user from a room cluster-wide. See Removing a user from a room.WebSocketClusterEnvelopeis a union onkind("publish"or"leaveUser"). Custom cluster bus code must accept both and forwardkind. An envelope withoutkindis treated aspublish.- Custom presence stores may implement the optional
getLiveNodeIds(). Without it,leaveUsertargets the nodes returned byresolveRoutefor the user audience. - Adapter:
@sonamu-kit/websocket-redis-adapter0.13.9 requiressonamu0.13.9 or later. - Mixed-version rolling deployment: among pre-0.13.9 nodes, only those on the Redis adapter reject control envelopes at schema validation instead of misreading them as
publish. Even so, a remote leave is not guaranteed until every node is upgraded. A pre-0.13.9 core behind a custom bus without validation may mishandle control envelopes, so upgrade all nodes before usingleaveUseron custom buses. Enabling the adapter and upgrading in the same deployment avoids the mixed window.
Migrating to 0.12
- Async mutations:
ctx.ws.join,leave,setUserId, andclearUserIdreturnPromise<void>. Addawait. They never reject, so existing calls withoutawaitkeep working, but code that relies on the store having applied the change mustawait. - Async publishes:
Sonamu.websocketRuntime.broadcast,publishToRoom,publishToUser, andpublishToAudiencereturnPromise<void>and never reject. - Async registration:
WebSocketRuntime#registerConnectionreturnsPromise<WebSocketConnection>andactivateConnectionreturnsPromise<void>. Code that drives the runtime directly mustawaitboth. - Typed user ID matching:
setUserId(1)no longer matchespublishToUser("1", ...). Bind and publish with the same type. - Invalid runtime publishes no longer close connections: an unknown event or a payload that fails validation is dropped for the affected route with
ws.publish.rejectedtelemetry. Recipients are no longer closed with1011.ctx.ws.publishstill throws. - Presence reads:
getRoomMembersreturns node-local snapshots. Useawait registry.getRoomMemberCount(roomId, namespace)for a cluster-wide count; checkpartial. - Default
nodeIdnow has a random suffix (${hostname()}-${process.pid}-${random}). Session IDs embed the node ID. - Custom stores and buses:
WebSocketPresenceStoreandWebSocketClusterBuschanged. Stores implementresolveRouteand may return promises. Envelopes carry encodedframesper route instead ofdata.subscribemay return a promise. - Shutdown waits up to
drainTimeoutMs(default5000) for pending store mutations and publishes.
Combining With Other Decorators
@websocket cannot share a method with @api, @stream, or @upload. If you want to expose the same data via both a WebSocket subscription and a plain HTTP endpoint, split them into two methods — one with @api, the other with @websocket.
Constraints
1. Cannot be combined with @api / @stream / @upload
2. httpMethod is always GET
@websocket automatically sets httpMethod: "GET" because the WebSocket upgrade starts from a GET request.
3. Watch out for context providers that depend on createSSE / reply
In the WebSocket path, SSE helpers andFastifyReply access are meaningless and raise an error immediately. If your context setup depends on them, define a dedicated websocketContextProvider.
Client Usage (Web)
For each@websocket method, Sonamu auto-generates a useWebSocketChannel hook.
useWebSocketChannel:
Logging
The@websocket decorator emits a debug log on each invocation.
Compared to @stream
Next Steps
@stream
When one-way SSE streaming is enough
@api
Build a standard REST endpoint
@transactional
Wrap mutations in a transaction
@cache
Improve performance with caching