Skip to main content
The @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
When Sonamu starts, it registers every @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 option
Inbound 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.
Guards run after the WebSocket upgrade and before the handler. When 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 in outEvents 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 call leave here.

ctx.ws.waitForClose

Keeps the handler alive until the connection closes. WebSocket methods typically await this promise to wrap up.

ctx.ws.join / ctx.ws.leave

Joins or leaves a room, which is the broadcast unit. Both return Promise<void>.

ctx.ws.setUserId / ctx.ws.clearUserId

Attaches a user identifier to the connection so it can be targeted by publishToUser. Both return Promise<void>.
User IDs match by type as well as value: a connection bound with 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 via Sonamu.websocketRuntime.
These methods never reject:
  • If the event is unknown to every route, or the payload fails a route’s outEvents schema, nothing is sent to that route’s connections, no connection is closed, and the runtime emits ws.publish.rejected telemetry. 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.
Publishes from one node reach every recipient, local or remote, in the order they were issued.
ctx.ws.publish keeps its synchronous behavior: an unknown event or invalid payload throws. Only the runtime publish methods above swallow validation failures.

Reading presence

Read APIs live on Sonamu.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.
Signature: leaveUser(userId: WebSocketUserId, roomId: WebSocketRoomId, namespace?: string): Promise<WebSocketLeaveUserResult>.
  • It removes every session bound to (namespace, userId) from roomId. An empty or omitted namespace means all namespaces. userId matches by type (1 and "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: true plus telemetry, like getRoomMemberCount.
Remote targets are every live node when the presence store implements the optional 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: false means 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 join while a leaveUser from another node is applied in between, the join is applied last and the user stays in the room.
Control envelopes use the same per-node publish queue and Redis command connection as publish envelopes, so one source node’s order is preserved: 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 with server.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.
Frames that arrive before the guards pass are held unparsed and processed in arrival order once the connection is activated. Each connection holds at most 100 frames; on overflow, the oldest frame is dropped and 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; unregister always comes after register.
  • resolveRoute splits an audience into the caller’s local session IDs and deduplicated remote node IDs, excluding inactive sessions. connections audiences are routed from the node ID embedded in each session ID without calling the store.
  • getRoomMemberCount counts active members across the cluster.
  • getLiveNodeIds is optional and returns every live node ID. leaveUser targets those nodes; without it, the runtime falls back to resolveRoute for the user audience.
  • User IDs must match by type (1 and "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 getRoomMemberCount waiting. Shutdown stops waiting for pending mutations and publishes after drainTimeoutMs.
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 kind unchanged. Receivers treat an envelope without kind as publish.
  • An envelope with an unknown kind or a schema failure is dropped, and the runtime emits ws.cluster.envelope.rejected. The Redis adapter reports it through the optional subscribe(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.
  • subscribe may return the unsubscribe function directly or through a promise. The runtime calls it once on shutdown. If subscribe fails, the runtime keeps working in local-only mode and reports it through telemetry.
  • Connections registered without a route key (for example, through registerConnection on 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.
Spread the adapter into server.websocket. The adapter’s nodeId, presenceStore, and clusterBus then share one node ID, so the runtime’s node ID check passes.
The 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 a duplicate() for pub/sub.
  • An existing RedisSentinel: you own it. The adapter subscribes on the Sentinel instance, so pub/sub follows failovers.
The adapter connects lazily on first use and never connects or closes clients you pass in. Call 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 Sentinel MASTER_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.
  • getRoomMemberCount counts 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_CHANGE schedules 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, EVALSHA that fails with NOSCRIPT is retried once after SCRIPT LOAD.
  • If the cluster bus subscription does not complete in time, subscribe rejects and the runtime reports ws.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.
If several applications share one Redis, give each one its own prefix. A client keyPrefix applies to keys but not to pub/sub channels, so two applications with the same prefix would receive each other’s cluster messages.

Migrating to 0.13.9

  • leaveUser: registry.leaveUser(userId, roomId, namespace?) and runtime.leaveUser(...) remove a user from a room cluster-wide. See Removing a user from a room.
  • WebSocketClusterEnvelope is a union on kind ("publish" or "leaveUser"). Custom cluster bus code must accept both and forward kind. An envelope without kind is treated as publish.
  • Custom presence stores may implement the optional getLiveNodeIds(). Without it, leaveUser targets the nodes returned by resolveRoute for the user audience.
  • Adapter: @sonamu-kit/websocket-redis-adapter 0.13.9 requires sonamu 0.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 using leaveUser on 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, and clearUserId return Promise<void>. Add await. They never reject, so existing calls without await keep working, but code that relies on the store having applied the change must await.
  • Async publishes: Sonamu.websocketRuntime.broadcast, publishToRoom, publishToUser, and publishToAudience return Promise<void> and never reject.
  • Async registration: WebSocketRuntime#registerConnection returns Promise<WebSocketConnection> and activateConnection returns Promise<void>. Code that drives the runtime directly must await both.
  • Typed user ID matching: setUserId(1) no longer matches publishToUser("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.rejected telemetry. Recipients are no longer closed with 1011. ctx.ws.publish still throws.
  • Presence reads: getRoomMembers returns node-local snapshots. Use await registry.getRoomMemberCount(roomId, namespace) for a cluster-wide count; check partial.
  • Default nodeId now has a random suffix (${hostname()}-${process.pid}-${random}). Session IDs embed the node ID.
  • Custom stores and buses: WebSocketPresenceStore and WebSocketClusterBus changed. Stores implement resolveRoute and may return promises. Envelopes carry encoded frames per route instead of data. subscribe may return a promise.
  • Shutdown waits up to drainTimeoutMs (default 5000) 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 and FastifyReply 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.
State returned from useWebSocketChannel:
Options:

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