Kind: Function
Source: packages/websockets/decorators/subscribe-message.decorator.ts
Part of: Websockets
Subscribes to messages that fulfils chosen pattern.
SubscribeMessage() marks a WebSocket gateway method as a handler for a specific incoming message pattern. When a connected client emits the matching event, NestJS routes the payload and socket context to the decorated method.
Signature
tsfunction SubscribeMessage(message: T): MethodDecorator
Parameters
| Name | Type |
|---|---|
message | T |
Returns: MethodDecorator
Diagram
mermaidgraph LR Client[WebSocket Client] -->|emit event + payload| Server[WebSocket Server] Server -->|match message pattern| Decorator["@SubscribeMessage('event')"] Decorator --> Handler[Gateway Handler Method] Handler -->|optional response| Client
Usage
tsimport {
ConnectedSocket,
MessageBody,
SubscribeMessage,
WebSocketGateway,
} from '@nestjs/websockets';
import { Socket } from 'socket.io';
@WebSocketGateway()
export class ChatGateway {
@SubscribeMessage('chat:message')
handleChatMessage(
@MessageBody() message: { text: string },
@ConnectedSocket() client: Socket,
) {
return {
event: 'chat:received',
data: {
clientId: client.id,
text: message.text,
},
};
}
}
AI Coding Instructions
- Apply
@SubscribeMessage()only to methods in classes configured as WebSocket gateways. - Use stable, descriptive message patterns such as
chat:messageoruser:updatedto avoid event-name collisions. - Extract incoming data with
@MessageBody()and connection details with@ConnectedSocket()rather than manually parsing handler arguments. - Validate and sanitize message payloads before performing business logic or broadcasting results.
- Return a
{ event, data }object when the handler should emit a response event back to the client.
Used by
12 references from 12 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.
Imported by (12)
ChatGateway—integration/inspector/src/chat/chat.gateway.ts:10AckGateway—integration/websockets/src/ack.gateway.ts:8ApplicationGateway—integration/websockets/src/app.gateway.ts:12CoreGateway—integration/websockets/src/core.gateway.ts:8ErrorGateway—integration/websockets/src/error.gateway.ts:8ExamplePathGateway—integration/websockets/src/example-path.gateway.ts:3NamespaceGateway—integration/websockets/src/namespace.gateway.ts:3ServerGateway—integration/websockets/src/server.gateway.ts:6
…and 4 more.
Was this page helpful?