🦅 NestJS Intermediate

How do you implement WebSocket support in NestJS?

Answer

NestJS supports WebSockets via Gateways — classes decorated with @WebSocketGateway(). A gateway is a component that listens for WebSocket events: @SubscribeMessage('message') handleMessage(client: Socket, payload: string) { this.server.emit('message', payload); }. Inject the server instance with @WebSocketServer() server: Server. Gateways are providers and can use dependency injection. NestJS supports two WebSocket adapters: socket.io (default, with rooms and namespaces) and ws (native, lighter). Guards and Pipes work with WebSocket handlers too. Gateways can be integrated into an HTTP/REST application — both run on the same port when using socket.io's default setup.