API Reference

MQTT.js

MQTT client for Node.js and the browser supporting publish, subscribe, QoS levels and reconnection.

Official Documentation ↗
CompatibilityThis documentation covers version mqtt v5.x / MQTT 3.1.1 与 5.0 / Node 18 LTS. Check the official docs for the latest API surface.

Installation

npmnpm install mqtt
pnpmpnpm add mqtt
yarnyarn add mqtt

Methods

Overview

MQTT.js is a client for the MQTT publish-subscribe protocol, common in IoT and messaging. It handles connection lifecycle, QoS, retained messages and automatic reconnection.

Core Methods

Connect to a broker, subscribe to topic filters with wildcards, publish payloads at a chosen QoS, and listen to message and event handlers. Options configure credentials, keepalive and last will.

Usage Notes

Use QoS 1 with idempotent handlers for reliable telemetry, set a last will to signal unexpected disconnects, and re-subscribe on reconnect or enable session persistence.

Common Pitfalls

Topic wildcards can widen a subscription beyond intent and flood the client. Ignoring QoS means messages may be lost. Retained messages can deliver stale state to new subscribers without warning.

Errors

The following points are quoted verbatim from the official documentation. 来源:https://cdn.jsdelivr.net/gh/mqttjs/MQTT.js@latest/README.md · 取证方式:HTTP GET 官方 README/文档页(HTML 去标签) · 抓取时间:2026-11-07T13:51:01.195Z. Any error type, throw condition or recovery step not stated there is left unspecified; this page does not infer exception classes or return values.

FAQ

Which QoS level should I use?
QoS 0 is at most once, QoS 1 at least once and QoS 2 exactly once. Higher levels add overhead, so use QoS 1 for most telemetry and accept idempotent handling of duplicates.
How does reconnection work?
The client reconnects automatically on connection loss and re-subscribes only if you enable that behavior. Persistent sessions let the broker queue messages for a returning client.
What does the retain flag do?
A retained publish is stored by the broker and delivered immediately to future subscribers, which is useful for last-known state topics but can surprise clients expecting only live messages.