Skip to content

WebSockets Guide

Build real-time features with the official WebSocket plugin and decorators. This guide matches current veloce-ts releases (see Changelog).

  • @WebSocket(path, options?) — marks a class as a WebSocket handler for that path; options declares who may connect (see Authenticated gateways).
  • @OnConnect / @OnMessage / @OnDisconnect — lifecycle hooks.
  • WebSocketPlugin — registers routes and performs runtime-specific upgrades (Bun / Deno / Node).
  • WebSocketConnection — send, broadcast, join, leave, close, the authenticated user, per-connection data, plus native WebSocket access.

One @OnMessage per class: metadata only stores a single message handler (the last @OnMessage wins if you declare more than one). Model different client payloads with one Zod schema (for example a discriminated union on a type field).

import 'reflect-metadata';
import {
VeloceTS,
WebSocketPlugin,
WebSocket,
OnConnect,
OnMessage,
OnDisconnect,
WebSocketConnection,
} from 'veloce-ts';
import { z } from 'zod';
const ChatMessage = z.object({
type: z.literal('chat'),
text: z.string().min(1),
});
@WebSocket('/ws/chat')
class ChatSocket {
@OnConnect()
onOpen(client: WebSocketConnection) {
client.join('lobby');
client.send({ type: 'welcome', message: 'Connected' });
}
@OnMessage(ChatMessage)
onData(client: WebSocketConnection, msg: z.infer<typeof ChatMessage>) {
client.broadcast({ type: 'chat', text: msg.text }, 'lobby');
}
@OnDisconnect()
onClose(client: WebSocketConnection) {
console.log('disconnected', client.id);
}
}
const app = new VeloceTS({ title: 'Chat', version: '1.0.0' });
app.usePlugin(new WebSocketPlugin());
app.include(ChatSocket);
await app.compile();
app.listen(3000);
  • Import WebSocketPlugin from veloce-ts (also available under veloce-ts/plugins).
  • The path is always the string passed to @WebSocket('/path'). The plugin constructor takes the options described under Connection hardening and Authenticated gateways; all are optional.
  • Call await app.compile() after controllers/handlers are include()d so metadata is compiled.
RuntimeUpgrade pathExtra install
BunBun.serve()’s native upgrade()—
DenoDeno.upgradeWebSocket()—
Node 20+@hono/node-ws (wraps ws)npm install @hono/node-ws

On Node the plugin needs the real http.Server, which only exists once app.listen() has run — so it injects the WebSocket handler in the plugin’s onStart() hook. Two consequences:

  • Serve with app.listen(). Handing app.fetch to a server you created yourself leaves the plugin without a server to attach to, and upgrades will not complete.
  • Node needs @hono/node-server too, which listen() already requires.

Forget @hono/node-ws and startup fails with the install command rather than a broken upgrade at runtime:

WebSocket support on Node requires the @hono/node-ws package.
Install it with: npm install @hono/node-ws

Heartbeat behaviour differs slightly by runtime — only Bun exposes a protocol-level ws.ping(); see the note under Connection hardening.

All four options are optional and set on WebSocketPlugin:

app.usePlugin(new WebSocketPlugin({
heartbeatIntervalMs: 30_000, // default 30 s; 0 disables
heartbeatTimeoutMs: 60_000, // default 2 × heartbeatIntervalMs
idleTimeoutMs: 0, // default 0 (disabled)
maxMessageSizeBytes: 1_048_576, // default 1 MiB
}));
OptionBehaviour
heartbeatIntervalMsHow often the server pings. Closes the connection with code 1001 if no inbound traffic arrives within heartbeatTimeoutMs.
heartbeatTimeoutMsLiveness deadline. Defaults to twice the interval.
idleTimeoutMsHard idle cutoff (code 1001) regardless of heartbeat replies. Set it larger than heartbeatIntervalMs if both are on, since pong replies count as activity.
maxMessageSizeBytesOversized inbound messages get an error frame and close code 1009 (Message Too Big).

Closed connections are removed from the connection registry and from every room they had joined.

Heartbeat protocol. On each tick the server sends a protocol-level ping where the runtime exposes one (Bun’s ws.ping()) plus a portable application-level {"type":"ping"} JSON frame. Liveness is measured by any inbound traffic, because protocol-level pong events are not observable from the manager — Bun delivers them to a pong handler on Bun.serve() that the adapter does not wire, and Deno’s upgraded sockets expose no ping() at all. Clients should reply with {"type":"pong"} or simply send any message within the timeout.

While the heartbeat is enabled, inbound {"type":"ping"} and {"type":"pong"} frames are reserved control messages and are not forwarded to your @OnMessage handlers.

Declare who may connect on the decorator:

import { WebSocket, OnConnect, type WebSocketConnection } from 'veloce-ts';
@WebSocket('/ws/notifications', { auth: true })
class NotificationsGateway {
@OnConnect()
onConnect(conn: WebSocketConnection) {
conn.join(`user:${conn.user!.sub}`); // the verified token payload
}
}
OptionEffect
auth: trueThe upgrade is refused with 401 unless the client is authenticated. The user is available as connection.user
roles: ['admin']Refused with 403 without one of the roles (implies auth). Goes through the RBAC plugin when installed — role inheritance and resolveRoles included — and through the token’s roles claim otherwise
closeOnTokenExpiryClose the connection with code 4401 when the access token it was opened with expires. Default true for gateways with auth or roles
rateLimit: { max, windowMs }Per-connection limit on inbound messages; see below

The refusal happens before the handshake on every runtime: the client sees a failed connection with an HTTP status, not an open socket that closes a moment later.

A gateway that asks for auth needs something to verify credentials with — AuthPlugin, or a verifyToken function passed to WebSocketPlugin. Otherwise the application fails at startup with a message saying so.

Implement authorizeUpgrade(c) for anything beyond “is authenticated”. It runs after the framework’s checks; return false (or throw) to refuse with 401, true to accept, or an object to accept and attach it to the connection as connection.data:

import type { Context } from 'hono';
import { WebSocket, OnConnect, type WebSocketConnection, type WebSocketGateway } from 'veloce-ts';
@WebSocket('/ws/rooms', { auth: true })
class RoomGateway implements WebSocketGateway<{ roomId: string }> {
async authorizeUpgrade(c: Context) {
const roomId = c.req.query('room');
const user = c.get('auth.user')!; // already verified
if (!roomId || !(await canJoin(user.sub, roomId))) return false;
return { roomId };
}
@OnConnect()
onConnect(conn: WebSocketConnection<{ roomId: string }>) {
conn.join(conn.data.roomId);
}
}

WebSocketGateway<TData> is optional — authorizeUpgrade is found by name — but it types the method and connection.data.

Browsers cannot set an Authorization header on a WebSocket. The usual workaround, the access token in the query string, puts a long-lived credential in URLs — and URLs end up in proxy logs, server logs and browser history.

Enable tickets by passing an auth section to the plugin:

app.usePlugin(new WebSocketPlugin({ auth: {} }));

That registers POST /ws/ticket. The client trades its normal credentials for a single-use ticket that expires in 30 seconds, and opens the socket with it:

// Browser
const { ticket } = await fetch('/ws/ticket', {
method: 'POST',
headers: { Authorization: `Bearer ${accessToken}` },
}).then((res) => res.json());
const ws = new WebSocket(`wss://api.example.com/ws/notifications?ticket=${ticket}`);

A ticket works once, never outlives the token it was issued from, and is useless to anyone who finds it in a log afterwards.

new WebSocketPlugin({
auth: {
sources: ['header', 'ticket'], // default when `auth` is given
ticket: {
ttlMs: 30_000, // default
path: '/ws/ticket', // default; `false` to register no endpoint
param: 'ticket', // query parameter name
store: sharedTicketStore, // default: in memory, single instance only
},
},
});
SourceClient sendsNotes
headerAuthorization: Bearer <token>Server-to-server and native clients. The only source when auth is omitted
ticket?ticket=<ticket>Recommended for browsers
query?token=<access token>Off by default. Kept for compatibility; the token ends up in logs

Carrying the token in the Sec-WebSocket-Protocol header is not supported.

A socket outlives the request that opened it, so revoking access has to reach open connections:

const manager = wsPlugin.getManager();
manager.disconnectUser(userId); // closes every connection of that user (code 4401)
manager.disconnectUser(userId, 4403, 'Removed from workspace');
manager.getUserConnections(userId); // WebSocketConnection[]

Call it on logout, when an account is suspended, or when a member loses access to what the socket serves. Connections of auth gateways also close on their own when their access token expires (closeOnTokenExpiry); the client reconnects with a fresh ticket.

@WebSocket('/ws/chat', { auth: true, rateLimit: { max: 20, windowMs: 10_000 } })

Messages over the limit are dropped and answered with { "error": "Rate limit exceeded", "retryAfterMs": … }; the connection stays open. Heartbeat frames do not count.

Since 3.7.0 gateway routes are registered after global middleware, so the authentication middleware and your own afterPlugins middleware run for upgrade requests. If you have a global middleware that rejects requests without credentials, it now rejects such upgrades too — exempt the gateway path there, or use { auth: true } with tickets.

TestClient.ws() connects to a gateway in-process — no server, no port. The upgrade goes through the real route (global middleware, authentication, authorizeUpgrade); only the transport is replaced.

import { TestClient } from 'veloce-ts/testing';
const client = new TestClient(app);
it('greets an authenticated client', async () => {
const ws = await client.withToken(token).ws('/ws/rooms', { query: { room: 'general' } });
expect(ws.connection.data).toEqual({ roomId: 'general' });
await ws.send({ type: 'chat', text: 'hello' });
expect(await ws.nextMessage()).toMatchObject({ type: 'chat', text: 'hello' });
await ws.close();
});
it('refuses an anonymous client', async () => {
await expect(client.ws('/ws/rooms')).rejects.toMatchObject({ status: 401 });
});
TestWebSocket
send(data)Deliver a message to @OnMessage and wait for the handler to finish
nextMessage(timeoutMs?)The next frame from the server not yet returned (default timeout 1 s)
messagesEvery frame the server has sent, JSON-parsed
close()Close from the client side; runs @OnDisconnect
closed, closeCode, closeReasonWhether — and how — the server closed the connection
connectionThe server-side WebSocketConnection, for assertions on user, data and rooms

It exercises the framework’s connection handling, not a runtime’s WebSocket transport. Keep one smoke test against a real server for that.

APIPurpose
idStable connection id
send(data)Send JSON-serializable data to this client
broadcast(data, room?)Send to every connection in a room, or all connections if room is omitted
join(room) / leave(room)Room membership
close(code?, reason?)Close the socket
userThe verified token payload of the client, when it authenticated during the upgrade; undefined otherwise
dataThe object returned by authorizeUpgrade(c); {} when it returned none
nativeUnderlying WebSocket instance

Optional Zod schema on @OnMessage(Schema) validates each incoming JSON payload. On failure the manager sends an error object to the client without tearing down the socket.

Since 3.0.0 only parse and schema failures — which describe the client’s own input — are reported back. If your handler itself throws (a failing query, a bug), the client receives a generic Internal server error and the real error is logged server-side, so driver messages and stack detail are no longer leaked over the socket.

The examples/chat-api project (Bun) shows REST + JWT + SQLite alongside WebSocket flow, including notes on 426/501 when upgrade is not available (e.g. plain fetch tests).