This document details the Socket.IO integration in NestJS, which provides a feature-rich WebSocket implementation with support for rooms, namespaces, broadcasting, and horizontal scaling. The integration is implemented through the @nestjs/platform-socket.io package, which serves as a platform adapter on top of the abstract @nestjs/websockets layer.
For native WebSocket support using the ws library, see Native WebSocket (WS) Integration. For the abstract WebSocket layer that both platforms build upon, this document references concepts from WebSocket Support.
The Socket.IO integration follows NestJS's platform adapter pattern, where an abstract WebSocket layer is implemented by a concrete Socket.IO adapter.
Sources: packages/platform-socket.io/package.json1-30 packages/websockets/package.json1-37 sample/02-gateways/package.json21-33
| Package | Version | Purpose | Peer Dependencies |
|---|---|---|---|
@nestjs/websockets | 11.1.13 | Abstract gateway interface, decorators, and lifecycle management | @nestjs/common, @nestjs/core, @nestjs/platform-socket.io (optional) |
@nestjs/platform-socket.io | 11.1.13 | Socket.IO-specific adapter implementation | @nestjs/common, @nestjs/websockets, rxjs |
socket.io | 4.8.3 | Core Socket.IO library with transport layer | Included as dependency |
@socket.io/redis-adapter | 8.3.0 | Redis-based pub/sub for horizontal scaling | Optional, used in distributed setups |
Sources: packages/platform-socket.io/package.json20-28 packages/websockets/package.json24-35
The Socket.IO adapter extends the abstract adapter pattern defined in @nestjs/websockets, implementing the WebSocketAdapter interface to provide Socket.IO-specific functionality.
The IoAdapter is the default WebSocket adapter when @nestjs/platform-socket.io is installed. The framework automatically selects it based on package availability. Applications can explicitly set the adapter during application initialization:
Sources: packages/platform-socket.io/package.json1-30 packages/core/package.json46-62
WebSocket gateways in NestJS are classes decorated with @WebSocketGateway, which accept Socket.IO server options.
The gateway decorator accepts both NestJS-specific options and Socket.IO server options:
| Option | Type | Description | Default |
|---|---|---|---|
port | number | WebSocket server port | Same as HTTP server |
namespace | string | Socket.IO namespace | / (root) |
cors | CorsOptions | CORS configuration | undefined |
transports | Transport[] | Allowed transport types | ['websocket', 'polling'] |
path | string | Socket.IO endpoint path | /socket.io |
adapter | Adapter | Custom adapter instance | Default adapter |
pingTimeout | number | Ping timeout in ms | 5000 |
pingInterval | number | Ping interval in ms | 25000 |
Sources: packages/websockets/package.json1-37 packages/platform-socket.io/package.json20-23
Socket.IO gateways use decorators to handle connection events and custom message events.
| Decorator | Purpose | Return Behavior |
|---|---|---|
@SubscribeMessage('event') | Subscribe to specific event | Return value emitted to client |
@MessageBody() | Extract message payload | Parameter decorator |
@ConnectedSocket() | Inject client socket | Parameter decorator |
@WebSocketServer() | Inject server instance | Property decorator |
Gateways can implement lifecycle interfaces:
OnGatewayInit: Called after server initialization with afterInit(server: Server)OnGatewayConnection: Called on client connection with handleConnection(client: Socket)OnGatewayDisconnect: Called on client disconnect with handleDisconnect(client: Socket)Sources: packages/websockets/package.json15-19 sample/02-gateways/package.json21-33
Socket.IO provides two key organizational features: namespaces for endpoint separation and rooms for grouping connections.
Rooms are managed through the Socket.IO client object:
| Operation | Method | Description |
|---|---|---|
| Join room | client.join('roomName') | Add client to room |
| Leave room | client.leave('roomName') | Remove client from room |
| Broadcast to room | server.to('roomName').emit('event', data) | Emit to all clients in room |
| Broadcast except sender | client.to('roomName').emit('event', data) | Emit to room excluding sender |
| Get room sockets | server.in('roomName').fetchSockets() | Get all sockets in room |
Each namespace maintains its own:
Multiple gateway classes can be created with different namespaces to separate concerns.
Sources: packages/platform-socket.io/package.json20-23 sample/02-gateways/package.json21-33
Socket.IO supports various broadcasting patterns for different distribution scenarios.
| Pattern | Implementation | Use Case |
|---|---|---|
| Acknowledge | Return value from @SubscribeMessage | Synchronous response to sender |
| Broadcast | server.emit('event', data) | Notify all clients |
| Room broadcast | server.to('room').emit('event', data) | Notify room members |
| Selective emit | client.to('room').emit('event', data) | Notify room except sender |
Sources: packages/platform-socket.io/package.json20-23
The @socket.io/redis-adapter enables Socket.IO to scale across multiple server instances by using Redis as a pub/sub message broker.
The Redis adapter requires:
Dependency: @socket.io/redis-adapter version 8.3.0
When a server emits an event:
This enables:
Sources: sample/02-gateways/package.json27 packages/platform-socket.io/package.json20-23
Socket.IO gateways integrate with NestJS's core dependency injection and module system.
Gateways are standard NestJS providers that support:
@WebSocketServer()forwardRef()| Phase | Gateway Hook | Core Integration |
|---|---|---|
| Module initialization | OnModuleInit | After DI container built |
| Server creation | afterInit(server) | Socket.IO server ready |
| Connection handling | handleConnection(client) | Per-client lifecycle |
| Disconnection | handleDisconnect(client) | Cleanup resources |
| Module destruction | OnModuleDestroy | Before app shutdown |
Sources: packages/websockets/package.json24-30 packages/core/package.json46-54
The @nestjs/platform-socket.io package implements the adapter interface required by @nestjs/websockets.
| Method | Parameters | Purpose |
|---|---|---|
create(port, options) | Port number, server options | Create and configure Socket.IO server |
bindClientConnect(server, callback) | Server, connection handler | Register connection listener |
bindClientDisconnect(client, callback) | Client socket, disconnect handler | Register disconnection listener |
bindMessageHandlers(client, handlers, transform) | Client, handler map, response transform | Bind event handlers to client |
close(server) | Server instance | Clean shutdown of server |
The adapter forwards Socket.IO configuration:
Sources: packages/platform-socket.io/package.json1-30 packages/websockets/package.json1-37
Socket.IO gateways can be tested using the @nestjs/testing module.
Testing Socket.IO gateways requires:
| Dependency | Purpose | Version |
|---|---|---|
@nestjs/testing | Testing utilities | 11.1.13 |
@nestjs/platform-socket.io | Socket.IO adapter | 11.1.13 |
socket.io-client | Client library for tests | Compatible with server version |
Sources: packages/testing/package.json1-38 sample/02-gateways/package.json34-58
The repository includes a comprehensive Socket.IO example demonstrating gateway implementation with Redis scaling support.
Location: sample/02-gateways/
Key Dependencies:
@nestjs/platform-socket.io: 11.1.13@nestjs/websockets: 11.1.13socket.io: 4.8.3@socket.io/redis-adapter: 8.3.0 (for scaling)redis: 5.10.0 (dev dependency for adapter)Features Demonstrated:
class-validator)Sources: sample/02-gateways/package.json1-77
NestJS provides two WebSocket platform adapters with different characteristics.
| Feature | @nestjs/platform-socket.io | @nestjs/platform-ws |
|---|---|---|
| Protocol | Socket.IO protocol | RFC 6455 WebSocket |
| Transport | WebSocket + long polling fallback | WebSocket only |
| Rooms | Built-in support | Manual implementation |
| Namespaces | Built-in support | Manual implementation |
| Broadcasting | Built-in with room targeting | Manual implementation |
| Scaling | Redis adapter available | Manual pub/sub required |
| Client library | socket.io-client required | Any WebSocket client |
| Bundle size | Larger (~socket.io overhead) | Minimal (native ws) |
| Standards compliance | Socket.IO protocol | Pure WebSocket standard |
| Auto-reconnection | Built-in client support | Manual implementation |
| Binary data | Automatic handling | Manual handling |
| Middleware | Built-in support | Manual implementation |
Socket.IO is preferred when:
For lightweight, standards-compliant WebSocket-only scenarios, see Native WebSocket (WS) Integration.
Sources: packages/platform-socket.io/package.json1-30 packages/platform-ws/package.json1-30
The Socket.IO integration maintains synchronized versions across the NestJS ecosystem.
| Package | Version | Socket.IO Version | Node.js |
|---|---|---|---|
@nestjs/platform-socket.io | 11.1.13 | 4.8.3 | >= 20 |
@nestjs/websockets | 11.1.13 | N/A | >= 20 |
@nestjs/core | 11.1.13 | N/A | >= 20 |
@socket.io/redis-adapter | 8.3.0 | 4.x compatible | >= 20 |
The platform adapter requires:
@nestjs/common: ^11.0.0@nestjs/websockets: ^11.0.0rxjs: ^7.1.0All packages use Lerna-coordinated versioning at 11.1.13.
Sources: lerna.json1-5 packages/platform-socket.io/package.json1-30 packages/core/package.json12-14
Refresh this wiki