# SubscribeMessage

**Kind:** Function

**Source:** [`packages/websockets/decorators/subscribe-message.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/decorators/subscribe-message.decorator.ts#L8)

**Part of:** [Websockets](subsystem-packages-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

| Name | Type |
|---|---|
| `message` | `T` |

**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)

- `ChatGateway` — `integration/inspector/src/chat/chat.gateway.ts`:10
- `AckGateway` — `integration/websockets/src/ack.gateway.ts`:8
- `ApplicationGateway` — `integration/websockets/src/app.gateway.ts`:12
- `CoreGateway` — `integration/websockets/src/core.gateway.ts`:8
- `ErrorGateway` — `integration/websockets/src/error.gateway.ts`:8
- `ExamplePathGateway` — `integration/websockets/src/example-path.gateway.ts`:3
- `NamespaceGateway` — `integration/websockets/src/namespace.gateway.ts`:3
- `ServerGateway` — `integration/websockets/src/server.gateway.ts`:6

…and 4 more.
