How to Use WebSocket in NestJS: Simple Guide with Example
In NestJS, you use WebSocket by creating a gateway class decorated with
@WebSocketGateway() and defining event handlers with @SubscribeMessage(). This setup allows your server to listen and respond to WebSocket events easily within the NestJS framework.Syntax
To use WebSocket in NestJS, you create a gateway class decorated with @WebSocketGateway(). Inside this class, you define methods to handle WebSocket events using @SubscribeMessage('eventName'). The gateway manages client connections and messages.
@WebSocketGateway(): Marks the class as a WebSocket gateway.@SubscribeMessage('eventName'): Decorates a method to handle a specific event.- Methods receive client and data parameters to interact with the connection.
typescript
import { WebSocketGateway, SubscribeMessage, MessageBody, ConnectedSocket } from '@nestjs/websockets'; import { Socket } from 'socket.io'; @WebSocketGateway() export class MyGateway { @SubscribeMessage('message') handleMessage(@MessageBody() data: string, @ConnectedSocket() client: Socket): string { return `Received: ${data}`; } }
Example
This example shows a simple NestJS WebSocket gateway that listens for a 'message' event from clients and replies with a confirmation string. It demonstrates how to set up the gateway and handle incoming messages.
typescript
import { Module } from '@nestjs/common'; import { WebSocketGateway, SubscribeMessage, MessageBody, ConnectedSocket } from '@nestjs/websockets'; import { Socket } from 'socket.io'; @WebSocketGateway() export class ChatGateway { @SubscribeMessage('message') handleMessage(@MessageBody() message: string, @ConnectedSocket() client: Socket): string { console.log(`Message from client ${client.id}: ${message}`); return `Server received: ${message}`; } } @Module({ providers: [ChatGateway], }) export class AppModule {}
Output
When a client sends a 'message' event with data 'Hello', the server logs: "Message from client <clientId>: Hello" and replies with "Server received: Hello".
Common Pitfalls
Common mistakes when using WebSocket in NestJS include:
- Not decorating the gateway class with
@WebSocketGateway(), so it won't register as a WebSocket server. - Forgetting to use
@SubscribeMessage()on event handler methods, so events are not caught. - Not injecting the gateway provider in the module, causing runtime errors.
- Mixing REST and WebSocket logic in the same method, which can confuse event handling.
Always keep WebSocket logic separate and use the proper decorators.
typescript
/* Wrong: Missing @WebSocketGateway decorator */ export class WrongGateway { @SubscribeMessage('test') handleTest() { return 'This will not work'; } } /* Right: Properly decorated gateway */ import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets'; @WebSocketGateway() export class RightGateway { @SubscribeMessage('test') handleTest() { return 'This works'; } }
Quick Reference
Here is a quick summary of key WebSocket decorators and their purpose in NestJS:
| Decorator | Purpose |
|---|---|
| @WebSocketGateway() | Marks a class as a WebSocket gateway to handle connections and events. |
| @SubscribeMessage('eventName') | Decorates a method to listen for a specific WebSocket event. |
| @MessageBody() | Injects the data sent by the client for the event. |
| @ConnectedSocket() | Injects the client socket instance for the connection. |
Key Takeaways
Use @WebSocketGateway() to create a WebSocket server in NestJS.
Handle events with methods decorated by @SubscribeMessage('eventName').
Inject client data and socket with @MessageBody() and @ConnectedSocket().
Always register your gateway provider in the module's providers array.
Keep WebSocket logic separate from REST to avoid confusion.