Node.js MQTT with RabbitMQ and LavinMQ

We recommend MQTT.js, the most widely used MQTT client for JavaScript.

npm install mqtt

Publish and subscribe

Set MQTT_HOST, MQTT_PORT, MQTT_USERNAME and MQTT_PASSWORD to the MQTT details on your instance’s details page in the CloudAMQP console. Port 8883 uses TLS. Without them, the examples connect to a local broker.

The examples are ES modules, so set "type": "module" in your package.json. Save the publisher as publisher.js:

import mqtt from "mqtt"

const port = Number(process.env.MQTT_PORT || 1883)
const client = await mqtt.connectAsync({
  host: process.env.MQTT_HOST || "localhost",
  port,
  protocol: port === 8883 ? "mqtts" : "mqtt",
  username: process.env.MQTT_USERNAME || "guest",
  password: process.env.MQTT_PASSWORD || "guest",
})

// QoS 1 resolves once the broker has sent its PUBACK
await client.publishAsync("hello", "Hello world!", { qos: 1 })
console.log(" [x] Sent 'Hello world!'")
await client.endAsync()

Save the subscriber as worker.js:

import mqtt from "mqtt"

const port = Number(process.env.MQTT_PORT || 1883)
const client = await mqtt.connectAsync({
  host: process.env.MQTT_HOST || "localhost",
  port,
  protocol: port === 8883 ? "mqtts" : "mqtt",
  username: process.env.MQTT_USERNAME || "guest",
  password: process.env.MQTT_PASSWORD || "guest",
})

// Each message is acked when the handler returns
client.on("message", (topic, message) => {
  console.log(` [x] Received '${message}'`)
})
await client.subscribeAsync("hello", { qos: 1 })
console.log(" [*] Waiting for messages. To exit press CTRL+C")

Run node worker.js in one terminal and node publisher.js in another.

A runnable example is in javascript/mqtt in cloudamqp/examples.

Good to know

  • Put the vhost in the username, as vhost:user. MQTT has no vhost of its own, and the console shows the username that way.
  • Keep certificate verification on. With protocol: "mqtts" MQTT.js verifies the server certificate; don’t set rejectUnauthorized: false.
  • Use QoS 1, so publishAsync resolves once the broker has sent its PUBACK, and each message is acked after the message handlers return.
  • MQTT.js reconnects automatically after a network failure, and subscribes again.
Was this page helpful?

Thanks for your feedback!