Skip to content

MessagePattern

reference
1 min readUpdated

Kind: Function

Source: packages/microservices/decorators/message-pattern.decorator.ts

Part of: Microservices

Subscribes to incoming messages which fulfils chosen pattern.

MessagePattern() marks a controller method as a handler for messages matching a specific request pattern. When a configured NestJS microservice transport receives a matching message, it invokes the decorated method and sends its return value back to the requester.

Signature

ts
function MessagePattern(metadata: T, transportOrExtras: Transport | symbol | Record<string, any>, maybeExtras: Record<string, any>): MethodDecorator

Parameters

NameType
metadataT
transportOrExtras`Transport
maybeExtrasRecord<string, any>

Returns: MethodDecorator

Diagram

mermaid
graph LR
  Client[Microservice Client] -->|send pattern + payload| Transport[Configured Transport]
  Transport --> Server[NestJS Microservice]
  Server -->|match pattern| Handler["@MessagePattern() handler"]
  Handler -->|response| Transport
  Transport --> Client

Usage

ts
import { Controller } from '@nestjs/common';
import { MessagePattern, Payload } from '@nestjs/microservices';

@Controller()
export class UsersController {
  @MessagePattern({ cmd: 'get_user' })
  async getUser(@Payload() userId: string) {
    return {
      id: userId,
      name: 'Ada Lovelace',
    };
  }
}

AI Coding Instructions

  • Apply @MessagePattern() to methods in controllers registered with a NestJS microservice application.
  • Use stable, shared pattern names or objects (for example, { cmd: 'get_user' }) that match the patterns sent by clients.
  • Return a value, Promise, or Observable when the caller expects a request-response result.
  • Use @Payload() to extract message data and @Ctx() when transport-specific context is required.
  • Use @EventPattern() instead for fire-and-forget events that do not require a response.

Used by

17 references from 17 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.

Imported by (17)

  • ExternalSvcControllerintegration/inspector/src/external-svc/external-svc.controller.ts:7
  • AppControllerintegration/microservices/src/app.controller.ts:20
  • KafkaMessagesControllerintegration/microservices/src/kafka/kafka.messages.controller.ts:9
  • KafkaConcurrentMessagesControllerintegration/microservices/src/kafka-concurrent/kafka-concurrent.messages.controller.ts:6
  • MqttBroadcastControllerintegration/microservices/src/mqtt/mqtt-broadcast.controller.ts:11
  • MqttControllerintegration/microservices/src/mqtt/mqtt.controller.ts:16
  • NatsBroadcastControllerintegration/microservices/src/nats/nats-broadcast.controller.ts:11
  • NatsControllerintegration/microservices/src/nats/nats.controller.ts:19

…and 9 more.

Was this page helpful?

Download as PDF
MessagePattern — NestJS head-to-head