Skip to content

JavaScript example ​

A minimal Node.js device client using mqtt.js. It assumes you have issued a device token and saved the bundle as described in Connecting a device:

  • client.pem: client certificate (clientCertPem)
  • client.key: client key (clientKeyPem)
  • server-ca.pem: server CA (serverCaCertPem)
bash
npm install mqtt
js
// device.mjs
import fs from "node:fs";
import mqtt from "mqtt";

const MQTT_URL = process.env.MQTT_URL;             // mqttUrl, e.g. mqtts://<broker-host>:8883
const CLIENT_ID = process.env.MQTT_CLIENT_ID;      // mqttClientId, the dtk_… token ID

const client = mqtt.connect(MQTT_URL, {
  clientId: CLIENT_ID,                              // must be the token ID, or data is ignored
  cert: fs.readFileSync("client.pem"),
  key: fs.readFileSync("client.key"),
  ca: fs.readFileSync("server-ca.pem"),
  rejectUnauthorized: true,
  maxVersion: "TLSv1.2",                            // the broker supports up to TLS 1.2
  keepalive: 30,
});

client.on("connect", () => {
  const message = {
    points: [
      { name: "temperature", value: 22.5, kind: "GAUGE", unit: "CELSIUS" },
      { name: "door_open", value: 0, kind: "STATUS", unit: "BOOLEAN" },
    ],
  };
  client.publish("s/metrics", JSON.stringify(message), { qos: 1 }, (err) => {
    if (err) console.error("publish failed", err);
    client.end();
  });
});

client.on("error", (err) => console.error("mqtt error", err.message));

Run it with:

bash
MQTT_URL='mqtts://<broker-host>:8883' MQTT_CLIENT_ID='dtk_<token-id>' node device.mjs

The publish callback only confirms that the broker received the message. Whether the points were recorded depends on the payload rules in Publishing metrics; check IoT → Metrics in the console.

Connect machines, automate workflows, and build custom apps for print production.