Skip to content

ServerMqtt

reference
2 min readUpdated

Kind: Class

Source: packages/microservices/server/server-mqtt.ts

Part of: Microservices

ServerMqtt is NestJS’s MQTT transport server implementation for microservices. It creates and manages an MQTT client connection, subscribes to message patterns, parses incoming packets, and dispatches them to registered message handlers. It also provides publishing support for request-response messaging and manages connection shutdown.

Extends: Server

Methods

MethodSignatureReturns
listenlisten(callback: (err?: unknown, ...optionalParams: unknown[]) => void)void
startstart(callback: (err?: unknown, ...optionalParams: unknown[]) => void)void
bindEventsbindEvents(mqttClient: MqttClient)void
closeclose()void
createMqttClientcreateMqttClient()MqttClient
getMessageHandlergetMessageHandler(pub: MqttClient)void
handleMessagehandleMessage(channel: string, buffer: Buffer, pub: MqttClient, originalPacket: Record<string, any>)Promise<any>
getPublishergetPublisher(client: MqttClient, context: MqttContext, id: string)any
parseMessageparseMessage(content: any)ReadPacket & PacketId
matchMqttPatternmatchMqttPattern(pattern: string, topic: string)void
getHandlerByPatterngetHandlerByPattern(pattern: string)`MessageHandler
removeHandlerKeySharedPrefixremoveHandlerKeySharedPrefix(handlerKey: string)void
getRequestPatterngetRequestPattern(pattern: string)string
getReplyPatterngetReplyPattern(pattern: string)string
registerErrorListenerregisterErrorListener(client: MqttClient)void
registerReconnectListenerregisterReconnectListener(client: MqttClient)void
registerDisconnectListenerregisterDisconnectListener(client: MqttClient)void
registerCloseListenerregisterCloseListener(client: MqttClient)void
registerConnectListenerregisterConnectListener(client: MqttClient)void
unwrapunwrap()T
onon(event: EventKey, callback: EventCallback)void
initializeSerializerinitializeSerializer(options: MqttOptions['options'])void

Properties

PropertyType
transportIdTransportId
urlstring
mqttClientMqttClient
pendingEventListenersArray<{ event: keyof MqttEvents; callback: MqttEvents[keyof MqttEvents]; }>

Where it refuses work

  • ServerMqtt stops the work with Error when !this.mqttClient — “Not initialized. Please call the "listen"/"startAllMicroservices" method before accessing…”.
  • ServerMqtt stops the work with an early return when isUndefined((packet as IncomingRequest).id).
  • ServerMqtt stops the work with an early return when !currentTopic && currentPattern !== MQTT_WILDCARD_ALL.
  • ServerMqtt stops the work with an early return when patternChar === MQTT_WILDCARD_ALL.
  • ServerMqtt stops the work with an early return when patternChar !== MQTT_WILDCARD_SINGLE && currentPattern !== currentTopic.
  • ServerMqtt stops the work with an early return when this.messageHandlers.has(route).

When something fails

  • ServerMqtt handles failure in 2 places: it logs it and continues in 1, and turns it into a return value in 1.

Diagram

mermaid
graph LR
  A[MQTT Broker] --> B[ServerMqtt]
  B --> C[MQTT Client]
  C --> D[bindEvents]
  D --> E[Incoming MQTT Packet]
  E --> F[parseMessage]
  F --> G[matchMqttPattern]
  G --> H[getMessageHandler]
  H --> I[handleMessage]
  I --> J[getPublisher]
  J --> A

Usage

ts
import { Controller } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import {
  MessagePattern,
  ServerMqtt,
} from '@nestjs/microservices';
import { AppModule } from './app.module';

@Controller()
class DeviceController {
  @MessagePattern('devices/+/temperature')
  handleTemperature(payload: { value: number; unit: string }) {
    return {
      received: true,
      temperature: payload.value,
    };
  }
}

async function bootstrap() {
  const mqttServer = new ServerMqtt({
    url: 'mqtt://localhost:1883',
  });

  const app = await NestFactory.createMicroservice(AppModule, {
    strategy: mqttServer,
  });

  await app.listen();
}

bootstrap();

AI Coding Instructions

  • Keep MQTT topic patterns aligned with @MessagePattern() handlers; wildcard topics must be compatible with MQTT matching rules.
  • Use ServerMqtt through NestJS microservice configuration rather than manually calling internal methods such as bindEvents() or handleMessage().
  • Ensure the MQTT broker URL and connection options are supplied through the transport options, including authentication or TLS settings when required.
  • Preserve packet parsing and publisher behavior when modifying request-response flows, as MQTT responses depend on packet identifiers and reply topics.
  • Always allow the NestJS application lifecycle to call close() so the MQTT client disconnects cleanly.

Relationships

  • IMPORTS → isObject
  • IMPORTS → isUndefined

Was this page helpful?

Download as PDF
ServerMqtt — NestJS head-to-head