stem-mqtt
v0.9.4
Published
MQTT 3.1.1 / 5.0 client and broker (Rust core, UniFFI Node bindings)
Maintainers
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-mqttimport * 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-mqttlistsstem-mqtt-linux-x64-gnu,stem-mqtt-linux-arm64-gnu,stem-mqtt-darwin-x64,stem-mqtt-darwin-arm64and@greenspand/stem-mqtt-win32-x64-msvc(scoped: npmjs.org's spam detection rejects the unscoped Windows name) as optional dependencies, each restricted to itsos/cpu(and glibc), so npm installs only the one your machine needs. On any other platformnpm installfails 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:
koffiships 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 areundefined. - Callbacks are plain objects with the interface's methods — no class needed:
{ on_message: (m) => …, on_disconnected: (reason) => … }.message.payloadis aUint8Array. - Or pull:
client.enable_message_queue(16), thenawait 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: brokerTlsLanguage notes
- Errors are classes named
MqttError<Variant>(mqtt.MqttErrorProtocol, …) — test withinstanceof. Publishing to a wildcard topic rejects withMqttErrorProtocol. - 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, notBuffer;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 packPublishing (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.EBADPLATFORMon install — there is no package for your OS/arch; build from source and copylibmqtt_client.*/libmqtt_broker.*intoclient/prebuilds/<platform>-<arch>/andbroker/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 oneruntime/between client and broker precisely to avoid this.SyntaxError: Cannot use import statement— the file isn't ESM; use.mjsor"type": "module".- Hangs at the end — see "The process may not exit".
