Skip to content

MessageBody

reference
1 min readUpdated

Kind: Function

Source: packages/websockets/decorators/message-body.decorator.ts

Part of: Websockets

MessageBody() binds a WebSocket handler parameter to the payload of an incoming message. It can also apply pipes to the full payload or a selected payload property before the handler receives the value.

Signature

ts
function MessageBody(propertyOrPipe: string | (Type<PipeTransform> | PipeTransform), pipes: (Type<PipeTransform> | PipeTransform)[]): ParameterDecorator

Parameters

NameType
propertyOrPipe`string
pipes`(Type

Returns: ParameterDecorator

Diagram

mermaid
graph LR
  Client[WebSocket client] --> Message[Incoming message payload]
  Message --> Decorator[@MessageBody()]
  Decorator --> Pipes[Configured pipes]
  Pipes --> Handler[Gateway handler parameter]

Usage

typescript
import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets';
import { ValidationPipe } from '@nestjs/common';
import { MessageBody } from '@nestjs/websockets';

class CreateCatDto {
  name: string;
  age: number;
}

@WebSocketGateway()
export class CatsGateway {
  @SubscribeMessage('createCat')
  create(
    @MessageBody(new ValidationPipe()) createDto: CreateCatDto,
  ) {
    return {
      event: 'catCreated',
      data: createDto,
    };
  }
}

AI Coding Instructions

  • Use @MessageBody() only on parameters of WebSocket gateway message handlers.
  • Pass pipes such as ValidationPipe when the message payload must be validated or transformed.
  • Keep the parameter type aligned with the expected client message payload.
  • Use a property name with @MessageBody('propertyName') when a handler only needs part of the payload.
  • Do not use @Body() for WebSocket handlers; it is intended for HTTP request bodies.

Relationships

  • IMPORTS → PipeTransform
  • IMPORTS → Type

Was this page helpful?

Download as PDF
MessageBody — NestJS head-to-head