
Security News
GitHub Actions Checkout Now Blocks Risky pull_request_target Checkouts
GitHub Actions checkout now blocks risky pull_request_target checkouts by default to help prevent pwn request supply chain attacks.
@fluojs/websockets
Advanced tools
Decorator-based WebSocket gateway authoring core for Fluo, with explicit Node, Bun, Deno, and Cloudflare Workers raw websocket bindings on dedicated subpaths.
English 한국어
Decorator-based WebSocket gateway authoring for the fluo runtime.
npm install @fluojs/websockets
The root Node.js entrypoint uses the package-owned ws dependency. Applications do not need to install ws separately unless they use it directly in their own code.
Use this package to add real-time WebSocket capabilities to your fluo application. It provides a clean, decorator-driven API for handling connections, messages, and disconnections, with first-class support for multiple runtimes (Node.js, Bun, Deno, Cloudflare Workers).
Use WebSocketModule.forRoot() when you want the default Node.js-backed websocket runtime.
import { WebSocketGateway, OnConnect, OnMessage, WebSocketModule } from '@fluojs/websockets';
import { Module } from '@fluojs/core';
@WebSocketGateway({ path: '/chat' })
class ChatGateway {
@OnConnect()
handleConnect(socket) {
console.log('Client connected');
}
@OnMessage('ping')
handlePing(payload, socket) {
socket.send(JSON.stringify({ event: 'pong', data: payload }));
}
}
@Module({
imports: [WebSocketModule.forRoot()],
providers: [ChatGateway],
})
export class AppModule {}
Multiple gateways can share the same path; their handlers will execute in discovery order.
@WebSocketGateway({ path: '/events' })
class MetricsGateway {
@OnMessage('metrics')
handleMetrics(data) { /* ... */ }
}
For server-backed Node adapters (Node.js, Express, Fastify), you can opt into a dedicated listener port. Use serverBacked.port: 0 when tests or dynamic hosts should let the operating system allocate an ephemeral listener port atomically. Fetch-style runtimes (@fluojs/websockets/bun, @fluojs/websockets/deno, and @fluojs/websockets/cloudflare-workers) reject serverBacked.
@WebSocketGateway({
path: '/chat',
serverBacked: { port: 3101 }
})
class DedicatedChatGateway {}
Use WebSocketModule.forRoot(...) to reject anonymous upgrades before the handshake completes and to tune the shared connection/payload limits.
import { UnauthorizedException } from '@fluojs/http';
WebSocketModule.forRoot({
limits: {
maxConnections: 500,
maxPayloadBytes: 65_536,
},
upgrade: {
guard(request) {
const authorization = request.headers.authorization;
if (authorization !== 'Bearer demo-token') {
throw new UnauthorizedException('Authentication required.');
}
},
},
});
When omitted, @fluojs/websockets applies bounded defaults for concurrent connections, inbound payload size, pending message buffers, and shutdown cleanup. Default settings are maxConnections: 1000, maxPayloadBytes: 1 MiB, buffer.maxPendingMessagesPerSocket: 256, shutdown.timeoutMs: 5000, Node heartbeat interval 30s, and Node backpressure maxBufferedAmountBytes: 1 MiB with drop behavior. Server-backed Node listeners enable heartbeat timers unless you explicitly set heartbeat.enabled to false. Node shutdown rejects in-flight async upgrades once shutdown begins, will close tracked websocket clients during application shutdown, and gives @OnDisconnect() cleanup a bounded chance to finish within shutdown.timeoutMs; unresolved cleanup is logged and bounded by that timeout instead of blocking shutdown indefinitely. The official fetch-style runtime modules (@fluojs/websockets/bun, @fluojs/websockets/deno, and @fluojs/websockets/cloudflare-workers) expose Request-typed upgrade guards and provide the same bounded close and disconnect cleanup behavior during application shutdown.
The root @fluojs/websockets / @fluojs/websockets/node guard receives Node's IncomingMessage. Fetch-style subpaths receive a Web-standard Request, so choose the subpath-specific WebSocketModuleOptions type when authoring reusable option objects.
WebSocketRoomService lets gateway or application services keep lightweight room membership state without reaching into adapter internals. Runtime lifecycle services implement joinRoom(socketId, room), leaveRoom(socketId, room), broadcastToRoom(room, event, data), and getRooms(socketId). broadcastToRoom(...) sends a JSON frame shaped as { event, data } to currently open sockets in the room and applies the configured backpressure policy before sending.
import { WebSocketRoomService } from '@fluojs/websockets';
class OrderStatusPublisher {
constructor(private readonly rooms: WebSocketRoomService) {}
publish(orderId: string, status: string) {
this.rooms.broadcastToRoom(`order:${orderId}`, 'order.status', { status });
}
}
Gateway @OnMessage() handlers receive one normalized payload contract across supported runtimes. Text frames are parsed as JSON when possible and otherwise delivered as strings. Binary frames are decoded as UTF-8 before the same JSON/event dispatch step, whether the runtime surfaces them as Node Buffer/typed arrays, Bun ArrayBuffer/views, Deno ArrayBuffer/views/Blob, or Cloudflare Workers ArrayBuffer/views/Blob. The limits.maxPayloadBytes check uses byte length for every representation and closes oversized accepted sockets with close code 1009.
@WebSocketGateway(options): Marks a class as a WebSocket gateway.@OnConnect(): Decorator for connection handlers.@OnMessage(event?): Decorator for inbound message handlers.@OnDisconnect(): Decorator for disconnection handlers.WebSocketModule: Root module for WebSocket integration.WebSocketModule.forRoot({ upgrade, limits, backpressure, buffer, heartbeat, shutdown }): Configures pre-upgrade guards and bounded runtime defaults.WebSocketGatewayLifecycleService: Root alias for the default Node.js-backed lifecycle service token.WebSocketRoomService: Room management contract implemented by runtime lifecycle services for joining, leaving, broadcasting to, and inspecting websocket rooms.defineWebSocketGatewayMetadata, getWebSocketGatewayMetadata, defineWebSocketHandlerMetadata, getWebSocketHandlerMetadata, getWebSocketHandlerMetadataEntries, webSocketGatewayMetadataSymbol, webSocketHandlerMetadataSymbol.Use the runtime subpaths when you want an explicit runtime binding instead of the default root Node.js alias. The root @fluojs/websockets entrypoint preserves the Node.js default module and lifecycle-service aliases. Fetch-style applications can import gateway decorators and metadata helpers from their selected runtime subpath so authoring code does not need to load the root Node.js-backed entrypoint.
The package manifest declares engines.node >=20.0.0 for the published package and default Node.js entrypoint. Bun, Deno, and Cloudflare Workers support is exposed through the dedicated fetch-style subpaths listed below; those subpaths keep request/handler types web-standard and avoid the root Node.js lifecycle-service alias in application code.
Each subpath exposes its *WebSocketModule.forRoot(...) entrypoint, the matching runtime lifecycle service export, and the shared gateway authoring primitives: WebSocketGateway, OnConnect, OnMessage, OnDisconnect, defineWebSocketGatewayMetadata, getWebSocketGatewayMetadata, defineWebSocketHandlerMetadata, getWebSocketHandlerMetadata, getWebSocketHandlerMetadataEntries, webSocketGatewayMetadataSymbol, and webSocketHandlerMetadataSymbol.
| Runtime | Subpath | Module | Lifecycle service |
|---|---|---|---|
| Node.js | @fluojs/websockets/node | NodeWebSocketModule | NodeWebSocketGatewayLifecycleService |
| Bun | @fluojs/websockets/bun | BunWebSocketModule | BunWebSocketGatewayLifecycleService |
| Deno | @fluojs/websockets/deno | DenoWebSocketModule | DenoWebSocketGatewayLifecycleService |
| Workers | @fluojs/websockets/cloudflare-workers | CloudflareWorkersWebSocketModule | CloudflareWorkersWebSocketGatewayLifecycleService |
import { BunWebSocketModule, OnMessage, WebSocketGateway } from '@fluojs/websockets/bun';
packages/websockets/src/module.test.tspackages/websockets/src/public-surface.test.tspackages/websockets/src/node/node.test.tspackages/websockets/src/bun/bun.test.tspackages/websockets/src/deno/deno.test.tspackages/websockets/src/cloudflare-workers/cloudflare-workers.test.tsFAQs
Decorator-based WebSocket gateway authoring core for Fluo, with explicit Node, Bun, Deno, and Cloudflare Workers raw websocket bindings on dedicated subpaths.
We found that @fluojs/websockets demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
GitHub Actions checkout now blocks risky pull_request_target checkouts by default to help prevent pwn request supply chain attacks.

Product
Socket now supports Custom Roles and Repository Access Permissions so organizations can control who can access specific repositories and actions.

Product
Socket MCP now lets AI assistants review org alerts, investigate threats using the Socket threat feed, and inspect package files in addition to dependency scoring.