🦅 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.
More NestJS Questions
View all →- Intermediate How does NestJS dependency injection scoping work?
- Intermediate What are NestJS microservices and what transports are supported?
- Intermediate What is the ExecutionContext in NestJS?
- Intermediate How do you implement role-based access control (RBAC) in NestJS?
- Intermediate What is the Reflector in NestJS and how is it used?