XUtils

MQTT.js

Client for MQTT - Pub-sub based messaging protocol for use on top of TCP/IP.


mqtt.js

Github Test Status codecov

Maintenance PRs Welcome

node npm NPM Downloads

MQTT.js is a client library for the MQTT protocol, written in JavaScript for node.js and the browser.

Example

For the sake of simplicity, let’s put the subscriber and the publisher in the same file:

const mqtt = require("mqtt");
const client = mqtt.connect("mqtt://test.mosquitto.org");

client.on("connect", () => {
  client.subscribe("presence", (err) => {
    if (!err) {
      client.publish("presence", "Hello mqtt");
    }
  });
});

client.on("message", (topic, message) => {
  // message is Buffer
  console.log(message.toString());
  client.end();
});

output:

Hello mqtt

React Native

MQTT.js can be used in React Native applications. To use it, see the React Native example

If you want to run your own MQTT broker, you can use Mosquitto or Aedes-cli, and launch it.

You can also use a test instance: test.mosquitto.org.

If you do not want to install a separate broker, you can try using the Aedes.

Import styles

CommonJS (Require)

const mqtt = require("mqtt")  // require mqtt
const client = mqtt.connect("mqtt://test.mosquitto.org")  // create a client

ES6 Modules (Import)

Default import

import mqtt from "mqtt"; // import namespace "mqtt"
let client = mqtt.connect("mqtt://test.mosquitto.org"); // create a client

Importing individual components

import { connect } from "mqtt"; // import connect from mqtt
let client = connect("mqtt://test.mosquitto.org"); // create a client

Command Line Tools

MQTT.js bundles a command to interact with a broker. In order to have it available on your path, you should install MQTT.js globally:

npm install mqtt -g

Then, on one terminal

mqtt sub -t 'hello' -h 'test.mosquitto.org' -v

On another

mqtt pub -t 'hello' -h 'test.mosquitto.org' -m 'from MQTT.js'

See mqtt help <command> for the command help.

Debug Logs

MQTT.js uses the debug package for debugging purposes. To enable debug logs, add the following environment variable on runtime :

# (example using PowerShell, the VS Code default)
$env:DEBUG='mqttjs*'

Customize Websockets with createWebsocket (Websocket Only)

When you need to add a custom websocket subprotocol or header to open a connection through a proxy with custom authentication this callback allows you to create your own instance of a websocket which will be used in the mqtt client.

  const createWebsocket = (url, websocketSubProtocols, options) => {
    const subProtocols = [
      websocketSubProtocols[0],
      'myCustomSubprotocolOrOAuthToken',
    ]
    return new WebSocket(url, subProtocols)
  }

  const client = await mqtt.connectAsync(<wss url>, {
    ...,
    createWebsocket: createWebsocket,
  });

Enabling Reconnection with reconnectPeriod option

To ensure that the mqtt client automatically tries to reconnect when the connection is dropped, you must set the client option reconnectPeriod to a value greater than 0. A value of 0 will disable reconnection and then terminate the final connection when it drops.

The default value is 1000 ms which means it will try to reconnect 1 second after losing the connection.

About Topic Alias Management

Enabling automatic Topic Alias using

If the client sets the option autoUseTopicAlias:true then MQTT.js uses existing topic alias automatically.

example scenario:

1. PUBLISH topic:'t1', ta:1                   (register)
2. PUBLISH topic:'t1'       -> topic:'', ta:1 (auto use existing map entry)
3. PUBLISH topic:'t2', ta:1                   (register overwrite)
4. PUBLISH topic:'t2'       -> topic:'', ta:1 (auto use existing map entry based on the receent map)
5. PUBLISH topic:'t1'                         (t1 is no longer mapped to ta:1)

User doesn’t need to manage which topic is mapped to which topic alias. If the user want to register topic alias, then publish topic with topic alias. If the user want to use topic alias, then publish topic without topic alias. If there is a mapped topic alias then added it as a property and update the topic to empty string.

Enabling automatic Topic Alias assign

If the client sets the option autoAssignTopicAlias:true then MQTT.js uses existing topic alias automatically. If no topic alias exists, then assign a new vacant topic alias automatically. If topic alias is fully used, then LRU(Least Recently Used) topic-alias entry is overwritten.

example scenario:

The broker returns CONNACK (TopicAliasMaximum:3)
1. PUBLISH topic:'t1' -> 't1', ta:1 (auto assign t1:1 and register)
2. PUBLISH topic:'t1' -> ''  , ta:1 (auto use existing map entry)
3. PUBLISH topic:'t2' -> 't2', ta:2 (auto assign t1:2 and register. 2 was vacant)
4. PUBLISH topic:'t3' -> 't3', ta:3 (auto assign t1:3 and register. 3 was vacant)
5. PUBLISH topic:'t4' -> 't4', ta:1 (LRU entry is overwritten)

Also user can manually register topic-alias pair using PUBLISH topic:‘some’, ta:X. It works well with automatic topic alias assign.

API


mqtt.connect([url], options)

Connects to the broker specified by the given url and options and returns a Client.

The URL can be on the following protocols: ‘mqtt’, ‘mqtts’, ‘tcp’, ‘tls’, ‘ws’, ‘wss’, ‘wxs’, ‘alis’. If you are trying to connect to a unix socket just append the +unix suffix to the protocol (ex: mqtt+unix). This will set the unixSocket property automatically.

The URL can also be an object as returned by URL.parse(), in that case the two objects are merged, i.e. you can pass a single object with both the URL and the connect options.

You can also specify a servers options with content: [{ host: 'localhost', port: 1883 }, ... ], in that case that array is iterated at every connect.

For all MQTT-related options, see the Client constructor.

connectAsync([url], options)

Asynchronous wrapper around the connect function.

Returns a Promise that resolves to a mqtt.Client instance when the client fires a 'connect' or 'end' event, or rejects with an error if the 'error' is fired.

Note that the manualConnect option will cause the promise returned by this function to never resolve or reject as the underlying client never fires any events.


Event 'connect'

function (connack) {}

Emitted on successful (re)connection (i.e. connack rc=0).

  • connack received connack packet. When clean connection option is false and server has a previous session for clientId connection option, then connack.sessionPresent flag is true. When that is the case, you may rely on stored session and prefer not to send subscribe commands for the client.

Event 'reconnect'

function () {}

Emitted when a reconnect starts.

Event 'close'

function () {}

Emitted after a disconnection.

Event 'disconnect'

function (packet) {}

Emitted after receiving disconnect packet from broker. MQTT 5.0 feature.

Event 'offline'

function () {}

Emitted when the client goes offline.

Event 'error'

function (error) {}

Emitted when the client cannot connect (i.e. connack rc != 0) or when a parsing error occurs.

The following TLS errors will be emitted as an error event:

  • ECONNREFUSED
  • ECONNRESET
  • EADDRINUSE
  • ENOTFOUND

Event 'end'

function () {}

Emitted when mqtt.Client#end() is called. If a callback was passed to mqtt.Client#end(), this event is emitted once the callback returns.

Event 'message'

function (topic, message, packet) {}

Emitted when the client receives a publish packet

  • topic topic of the received packet
  • message payload of the received packet
  • packet received packet, as defined in mqtt-packet

Event 'packetsend'

function (packet) {}

Emitted when the client sends any packet. This includes .published() packets as well as packets used by MQTT for managing subscriptions and connections

Event 'packetreceive'

function (packet) {}

Emitted when the client receives any packet. This includes packets from subscribed topics as well as packets used by MQTT for managing subscriptions and connections


mqtt.Client#connect()

By default client connects when constructor is called. To prevent this you can set manualConnect option to true and call client.connect() manually.

mqtt.Client#publish(topic, message, [options], [callback])

Publish a message to a topic

  • topic is the topic to publish to, String
  • message is the message to publish, Buffer or String
  • options is the options to publish with, including:
    • qos QoS level, Number, default 0
    • retain retain flag, Boolean, default false
    • dup mark as duplicate flag, Boolean, default false
    • properties: MQTT 5.0 properties object
      • payloadFormatIndicator: Payload is UTF-8 Encoded Character Data or not boolean,
      • messageExpiryInterval: the lifetime of the Application Message in seconds number,
      • topicAlias: value that is used to identify the Topic instead of using the Topic Name number,
      • responseTopic: String which is used as the Topic Name for a response message string,
      • correlationData: used by the sender of the Request Message to identify which request the Response Message is for when it is received binary,
      • userProperties: The User Property is allowed to appear multiple times to represent multiple name, value pairs object,
      • subscriptionIdentifier: representing the identifier of the subscription number,
      • contentType: String describing the content of the Application Message string
    • cbStorePut - function (), fired when message is put into outgoingStore if QoS is 1 or 2.
  • callback - function (err), fired when the QoS handling completes, or at the next tick if QoS 0. An error occurs if client is disconnecting.

mqtt.Client#publishAsync(topic, message, [options])

Async publish. Returns a Promise<void>.


mqtt.Client#subscribeAsync(topic/topic array/topic object, [options])

Async subscribe. Returns a Promise<granted[]>.


mqtt.Client#unsubscribe(topic/topic array, [options], [callback])

Unsubscribe from a topic or topics

  • topic is a String topic or an array of topics to unsubscribe from
  • options: options of unsubscribe.
    • properties: object
      • userProperties: The User Property is allowed to appear multiple times to represent multiple name, value pairs object
  • callback - function (err), fired on unsuback. An error occurs if client is disconnecting.

mqtt.Client#unsubscribeAsync(topic/topic array, [options])

Async unsubscribe. Returns a Promise<void>.


mqtt.Client#end([force], [options], [callback])

Close the client, accepts the following options:

  • force: passing it to true will close the client right away, without waiting for the in-flight messages to be acked. This parameter is optional.
  • options: options of disconnect.
    • reasonCode: Disconnect Reason Code number
    • properties: object
      • sessionExpiryInterval: representing the Session Expiry Interval in seconds number,
      • reasonString: representing the reason for the disconnect string,
      • userProperties: The User Property is allowed to appear multiple times to represent multiple name, value pairs object,
      • serverReference: String which can be used by the Client to identify another Server to use string
  • callback: will be called when the client is closed. This parameter is optional.

mqtt.Client#endAsync([force], [options])

Async end. Returns a Promise<void>.


mqtt.Client#removeOutgoingMessage(mId)

Remove a message from the outgoingStore. The outgoing callback will be called with Error(‘Message removed’) if the message is removed.

After this function is called, the messageId is released and becomes reusable.

  • mId: The messageId of the message in the outgoingStore.

mqtt.Client#reconnect()

Connect again using the same options as connect()


mqtt.Client#connected

Boolean : set to true if the client is connected. false otherwise.


mqtt.Client#getLastMessageId()

Number : get last message id. This is for sent messages only.


mqtt.Client#reconnecting

Boolean : set to true if the client is trying to reconnect to the server. false otherwise.


mqtt.Store(options)

In-memory implementation of the message store.

  • options is the store options:
    • clean: true, clean inflight messages when close is called (default true)

Other implementations of mqtt.Store:


mqtt.Store#put(packet, callback)

Adds a packet to the store, a packet is anything that has a messageId property. The callback is called when the packet has been stored.


mqtt.Store#createStream()

Creates a stream with all the packets in the store.


mqtt.Store#del(packet, cb)

Removes a packet from the store, a packet is anything that has a messageId property. The callback is called when the packet has been removed.


mqtt.Store#close(cb)

Closes the Store.

Bundle

MQTT.js is bundled using esbuild. It is tested working with all bundlers like Webpack, Vite and React.

You can find all mqtt bundles versions in dist folder:

  • mqtt.js - iife format, not minified
  • mqtt.min.js - iife format, minified
  • mqtt.esm.js - esm format minified

Starting from MQTT.js > 5.2.0 you can import mqtt in your code like this:

import mqtt from 'mqtt'

This will be automatically handled by your bundler.

Otherwise you can choose to use a specific bundle like:

import * as mqtt from 'mqtt/dist/mqtt'
import * as mqtt from 'mqtt/dist/mqtt.min'
import mqtt from 'mqtt/dist/mqtt.esm'

Via CDN

The MQTT.js bundle is available through http://unpkg.com, specifically at https://unpkg.com/mqtt/dist/mqtt.min.js. See http://unpkg.com for the full documentation on version ranges.

About QoS

Here is how QoS works:

  • QoS 0 : received at most once : The packet is sent, and that’s it. There is no validation about whether it has been received.
  • QoS 1 : received at least once : The packet is sent and stored as long as the client has not received a confirmation from the server. MQTT ensures that it will be received, but there can be duplicates.
  • QoS 2 : received exactly once : Same as QoS 1 but there is no duplicates.

About data consumption, obviously, QoS 2 > QoS 1 > QoS 0, if that’s a concern to you.

Contributors

MQTT.js is only possible due to the excellent work of the following contributors:

Name GitHub Twitter
Adam Rudd GitHub/adamvr Twitter/@adam_vr
Matteo Collina GitHub/mcollina Twitter/@matteocollina
Maxime Agor GitHub/4rzael Twitter/@4rzael
Siarhei Buntsevich GitHub/scarry1992
Daniel Lando GitHub/robertsLando


Articles

  • coming soon...