Skip to content

SubscribeMessage

reference
1 min readUpdated

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

ts
function SubscribeMessage(message: T): MethodDecorator

Parameters

NameType
messageT

Returns: MethodDecorator

Diagram

mermaid
graph 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

ts
import {
  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:message or user:updated to 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)

  • ChatGatewayintegration/inspector/src/chat/chat.gateway.ts:10
  • AckGatewayintegration/websockets/src/ack.gateway.ts:8
  • ApplicationGatewayintegration/websockets/src/app.gateway.ts:12
  • CoreGatewayintegration/websockets/src/core.gateway.ts:8
  • ErrorGatewayintegration/websockets/src/error.gateway.ts:8
  • ExamplePathGatewayintegration/websockets/src/example-path.gateway.ts:3
  • NamespaceGatewayintegration/websockets/src/namespace.gateway.ts:3
  • ServerGatewayintegration/websockets/src/server.gateway.ts:6

…and 4 more.

Was this page helpful?

Download as PDF
SubscribeMessage — NestJS head-to-head