npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

stem-mqtt

v0.9.4

Published

MQTT 3.1.1 / 5.0 client and broker (Rust core, UniFFI Node bindings)

Readme

Node.js / TypeScript

ESM bindings generated by uniffi-bindgen-node-js, loading the Rust library through koffi. One npm package with two entry points. Read the shared concepts first for the option records and semantics.

Install

npm install stem-mqtt
import * as mqtt from "stem-mqtt/client";
import * as brk from "stem-mqtt/broker";

The package is stem-mqtt on npmjs.org. On GitHub Packages and the Gitea registry it is published as @<owner>/stem-mqtt-node (those registries require the scope to match the owner). It replaces the earlier hand-written napi-rs addon stem-mqtt-client, which had no broker.

Requirements

  • Node.js 16+ (ESM — use "type": "module" or .mjs). Server-side only; there is no browser build (browsers can talk to the broker's WebSocket port with any MQTT.js client instead).
  • The native libraries come in one package per platform, installed automatically: stem-mqtt lists stem-mqtt-linux-x64-gnu, stem-mqtt-linux-arm64-gnu, stem-mqtt-darwin-x64, stem-mqtt-darwin-arm64 and @greenspand/stem-mqtt-win32-x64-msvc (scoped: npmjs.org's spam detection rejects the unscoped Windows name) as optional dependencies, each restricted to its os / cpu (and glibc), so npm installs only the one your machine needs. On any other platform npm install fails up front (EBADPLATFORM). With --omit=optional (or a lockfile made on another OS) the platform package is missing: install it explicitly, e.g. npm install stem-mqtt-linux-x64-gnu.
  • No compiler is needed at install time: koffi ships prebuilt binaries.

Quick start

import * as mqtt from "stem-mqtt/client";
import * as brk from "stem-mqtt/broker";

const broker = new brk.MqttBroker({
  bind_address: "127.0.0.1", port: 0, ws_port: undefined, allow_anonymous: true, max_clients: 0,
  max_qos: brk.QoS.ExactlyOnce, max_retained_messages: 100, max_queued_per_client: 100,
  redelivery_interval_secs: 0, tls: undefined, max_packet_size: 0, max_outbound_queue: 0,
  session_expiry_secs: 0,
});
await broker.start();
const port = broker.bound_port();

const options = (client_id) => ({
  host: "127.0.0.1", port, client_id, version: mqtt.MqttVersion.V5, clean_start: true,
  keep_alive_secs: 30, username: undefined, password: undefined, will: undefined,
  connect_timeout_secs: 10, operation_timeout_secs: 5, auto_reconnect: false,
  reconnect_backoff_secs: 0, reconnect_max_backoff_secs: 0, tls: undefined,
  max_packet_size: 0, auth_method: undefined, auth_data: undefined,
});

let resolveMessage;
const got = new Promise((resolve) => (resolveMessage = resolve));
const sub = new mqtt.MqttClient(options("node-sub"));
sub.set_message_listener({ on_message: resolveMessage, on_disconnected: () => {} });
await sub.connect();
await sub.subscribe("demo/#", mqtt.QoS.AtLeastOnce);

const pub = new mqtt.MqttClient(options("node-pub"));
await pub.connect();
await pub.publish("demo/hello", new TextEncoder().encode("hello"), mqtt.QoS.AtLeastOnce, false);

const message = await got;
console.log(message.topic, new TextDecoder().decode(message.payload));

await pub.disconnect(); await sub.disconnect(); await broker.stop();
process.exit(0);   // see "Language notes"

Client

  • Methods return Promises: connect(), subscribe(filter, qos), unsubscribe(filter), publish(topic, payload: Uint8Array, qos, retain), disconnect(). is_connected(), set_message_listener(), enable_message_queue(), last_disconnect_reason() are synchronous.
  • Property and method names keep the Rust snake_case (client_id, keep_alive_secs, set_message_listener).
  • Enums are PascalCase members: mqtt.QoS.AtMostOnce | AtLeastOnce | ExactlyOnce, mqtt.MqttVersion.V311 | V5. Optional values are undefined.
  • Callbacks are plain objects with the interface's methods — no class needed: { on_message: (m) => …, on_disconnected: (reason) => … }. message.payload is a Uint8Array.
  • Or pull: client.enable_message_queue(16), then await client.next_message(5000) → a message, or nothing if the timeout passes.

Broker

new brk.MqttBroker(config); await start(), await stop(), is_running(), bound_port(), bound_ws_port(), bound_tls_port(), client_count(). Every config field is required (the generator has no default arguments): pass 0 / undefined for the ones you don't need.

broker.set_event_listener({
  on_client_connected: (id) => console.log("+", id),
  on_client_disconnected: (id, reason) => console.log("-", id, reason),
  on_message_published: (id, topic, qos) => console.log(id, "->", topic),
});
// or: broker.enable_event_queue(64); const event = await broker.next_event(1000);

Authentication

broker.set_auth_provider({
  authenticate: (clientId, username, password) => username === "demo" && password !== undefined,
});

A refused client makes await client.connect() reject. Enhanced authentication (as in the test):

broker.set_enhanced_auth_provider({
  step: (_id, _method, data, round) =>
    round === 0
      ? { outcome: brk.EnhancedAuthOutcome.Continue, data: new Uint8Array([7]) }
      : data && data[0] === 8
        ? { outcome: brk.EnhancedAuthOutcome.Success, data: new TextEncoder().encode("welcome") }
        : { outcome: brk.EnhancedAuthOutcome.Failure, data: new Uint8Array() },
});

const client = new mqtt.MqttClient({ ...options("node-eauth"), auth_method: "X-ADD-ONE",
                                     auth_data: new TextEncoder().encode("hello") });
client.set_auth_handler({ respond: (_method, challenge) => challenge.map((b) => b + 1) });
await client.connect();

TLS

import { readFileSync } from "node:fs";
const tls = { ca_cert_pem: readFileSync("ca.pem"), client_cert_pem: undefined,
              client_key_pem: undefined, insecure_skip_certificate_verification: false };
// client: { ...options("c"), tls }

const brokerTls = { port: 8883, cert_pem: readFileSync("server.pem"),
                    key_pem: readFileSync("server.key"), client_ca_pem: undefined };
// broker config: tls: brokerTls

Language notes

  • Errors are classes named MqttError<Variant> (mqtt.MqttErrorProtocol, …) — test with instanceof. Publishing to a wildcard topic rejects with MqttErrorProtocol.
  • The process may not exit on its own while the native library holds handles; call process.exit() when you are done (the smoke test does).
  • Packet payloads are Uint8Array, not Buffer; Buffer.from(u8) converts.

Building from source

cargo rustc --release -p stem-mqtt-client --lib --crate-type cdylib
cargo rustc --release -p stem-mqtt-broker --lib --crate-type cdylib
nu scripts/install_bindgens.nu node
nu scripts/publish_packages.nu stage node      # dist/node/{client,broker,runtime}/ + this host's native libs
cd dist/node && npm pack

Publishing (publish_packages.nu publish node …) moves the libraries into one package per platform under dist/node/platforms/<target>/ and publishes those before the main package. Release CI passes --natives native-libs: every target's libraries, built by scripts/ci/native_libs.nu.

The package layout is client/, broker/ and one shared runtime/ — the generator emits a copy of the runtime per component, and two copies cannot be loaded into one process because they register the same named types in koffi.

The end-to-end test is tests/bindings/node/smoke.mjs (nu scripts/test_bindings.nu node).

Troubleshooting

  • Cannot find module './client/index.js' — import the package entry points (stem-mqtt/client), not a path.
  • EBADPLATFORM on install — there is no package for your OS/arch; build from source and copy libmqtt_client.* / libmqtt_broker.* into client/prebuilds/<platform>-<arch>/ and broker/prebuilds/<platform>-<arch>/ of the installed package.
  • Failed to load shared library — the platform package was not installed (optional dependencies omitted); npm install stem-mqtt-<platform>-<arch>[-gnu] (on Windows @greenspand/stem-mqtt-win32-x64-msvc) of the same version.
  • Duplicate type name 'RustBuffer' — you are using separately generated components; the published package shares one runtime/ between client and broker precisely to avoid this.
  • SyntaxError: Cannot use import statement — the file isn't ESM; use .mjs or "type": "module".
  • Hangs at the end — see "The process may not exit".