WebSocket Gateways with the Socket.IO Adapter
Implement @WebSocketGateway handlers, rooms, and lifecycle hooks for live communication.
Why Gateways Exist
REST handles request/response, but real-time features (chat, presence, live dashboards) need a persistent, bidirectional channel. NestJS wraps this with a WebSocket Gateway.
- A gateway is a provider decorated with
@WebSocketGateway(). - By default Nest uses the Socket.IO platform adapter (
@nestjs/platform-socket.io). - Gateways are normal Nest classes: they support dependency injection, guards, pipes, and interceptors just like controllers.
Install the deps with npm i @nestjs/websockets @nestjs/platform-socket.io socket.io.
Declaring a Gateway
Decorate a class with @WebSocketGateway() and register it as a provider in a module. You can pass a port and options such as namespace and CORS config.
@SubscribeMessage('event')binds a handler to an inbound Socket.IO event.- The return value (or a
WsResponse) is emitted back to the calling client.
Below, clients sending ping receive a pong reply.
import { WebSocketGateway, SubscribeMessage, MessageBody } from '@nestjs/websockets';
@WebSocketGateway({ namespace: '/chat', cors: { origin: '*' } })
export class ChatGateway {
@SubscribeMessage('ping')
handlePing(@MessageBody() data: string): { event: string; data: string } {
return { event: 'pong', data: `received: ${data}` };
}
}All lessons in this course
- WebSocket Gateways with the Socket.IO Adapter
- Authenticating and Guarding Socket Connections
- Server-Sent Events for One-Way Push
- Scaling Realtime with a Redis Pub/Sub Adapter