SkillAgentSearch skills...

MQTT.js

The MQTT client for Node.js and the browser

Install / Use

/learn @mqttjs/MQTT.js
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

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.

Table of Contents

MQTT.js is an OPEN Open Source Project, see the Contributing section to find out what this means.

JavaScript Style
Guide

<a name="notes"></a>

Important notes for existing users

v5.0.0 (07/2023)

  • Removes support for all end of life node versions (v12 and v14), and now supports node v18 and v20.
  • Completely rewritten in Typescript 🚀.
  • When creating MqttClient instance new is now required.

v4.0.0 (Released 04/2020) removes support for all end of life node versions, and now supports node v12 and v14. It also adds improvements to debug logging, along with some feature additions.

As a breaking change, by default a error handler is built into the MQTT.js client, so if any errors are emitted and the user has not created an event handler on the client for errors, the client will not break as a result of unhandled errors. Additionally, typical TLS errors like ECONNREFUSED, ECONNRESET have been added to a list of TLS errors that will be emitted from the MQTT.js client, and so can be handled as connection errors.

v3.0.0 adds support for MQTT 5, support for node v10.x, and many fixes to improve reliability.

Note: MQTT v5 support is experimental as it has not been implemented by brokers yet.

v2.0.0 removes support for node v0.8, v0.10 and v0.12, and it is 3x faster in sending packets. It also removes all the deprecated functionality in v1.0.0, mainly mqtt.createConnection and mqtt.Server. From v2.0.0, subscriptions are restored upon reconnection if clean: true. v1.x.x is now in LTS, and it will keep being supported as long as there are v0.8, v0.10 and v0.12 users.

As a breaking change, the encoding option in the old client is removed, and now everything is UTF-8 with the exception of the password in the CONNECT message and payload in the PUBLISH message, which are Buffer.

Another breaking change is that MQTT.js now defaults to MQTT v3.1.1, so to support old brokers, please read the client options doc.

v1.0.0 improves the overall architecture of the project, which is now split into three components: MQTT.js keeps the Client, mqtt-connection includes the barebone Connection code for server-side usage, and mqtt-packet includes the protocol parser and generator. The new Client improves performance by a 30% factor, embeds Websocket support (MOWS is now deprecated), and it has a better support for QoS 1 and 2. The previous API is still supported but deprecated, as such, it is not documented in this README.

<a name="install"></a>

Installation

npm install mqtt --save

<a name="example"></a>

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

<a name="example-react-native"></a>

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.

<a name="import_styles"></a>

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

<a name="cli"></a>

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.

<a name="debug"></a>

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*'

<a name="reconnecting"></a>

About Reconnection

An important part of any websocket connection is what to do when a connection drops off and the client needs to reconnect. MQTT has built-in reconnection support that can be configured to behave in ways that suit the application.

Refresh Authentication Options / Signed Urls with transformWsUrl (Websocket Only)

When an mqtt connection drops and needs to reconnect, it's common to require that any authentication associated with the connection is kept current with the underlying auth mechanism. For instance some applications may pass an auth token with connection options on the initial connection, while other cloud services may require a url be signed with each connection.

By the time the reconnect happens in the application lifecycle, the original auth data may have expired.

To address this we can use a hook called transformWsUrl to manipulate either of the connection url or the client options at the time of a reconnect.

Example (update clientId & username on each reconnect):

    const transformWsUrl = (url, options, client) => {
      client.options.username = `token=${this.get_current_auth_token()}`;
      client.options.clientId = `${this.get_updated_clientId()}`;

      return `${this.get_signed_cloud_url(url)}`;
    }

    const connection = await mqtt.connectAsync(<wss url>, {
      ...,
      transformWsUrl: transformUrl,
    });

Now every time a new WebSocket connection is opened (hopefully not too often), we will get a fresh signed url or fresh auth token data.

Note: Currently this hook does not support promises, meaning that in order to use the latest auth token, you must have some outside mechanism running that handles application-level authentication refreshing so that the websocket connection can simply grab the latest valid token or signed url.

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.

Note that this will only enable reconnects after either a connection timeout, or after a successful connection. It will not (by default) enable retrying connections that are actively denied with a CONNACK error by the server.

To also enable automatic reconnects for CONNACK errors, set reconnectOnConnackError: true.

<a name="topicalias"></a>

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.

Related Skills

View on GitHub
GitHub Stars9.0k
CategoryDevelopment
Updated11h ago
Forks1.4k

Languages

TypeScript

Security Score

85/100

Audited on Mar 20, 2026

No findings