0
0
Drone-programmingHow-ToBeginner · 4 min read

How to Implement MQTT in Node.js: Simple Guide with Example

To implement MQTT in Node.js, install the mqtt package and use it to connect to an MQTT broker. Then, you can publish and subscribe to topics using simple methods like client.publish() and client.subscribe().
📐

Syntax

The basic syntax to use MQTT in Node.js involves importing the mqtt package, connecting to a broker, and then subscribing or publishing to topics.

  • mqtt.connect(brokerUrl, options): Connects to the MQTT broker.
  • client.subscribe(topic): Subscribes to a topic to receive messages.
  • client.publish(topic, message): Sends a message to a topic.
  • client.on('message', callback): Listens for messages on subscribed topics.
javascript
const mqtt = require('mqtt');

const client = mqtt.connect('mqtt://broker.hivemq.com');

client.on('connect', () => {
  client.subscribe('your/topic');
  client.publish('your/topic', 'Hello MQTT');
});

client.on('message', (topic, message) => {
  console.log(`Received message: ${message.toString()} on topic: ${topic}`);
});
💻

Example

This example connects to a public MQTT broker, subscribes to a topic, and publishes a message. It then logs any received messages on that topic.

javascript
const mqtt = require('mqtt');

const client = mqtt.connect('mqtt://broker.hivemq.com');

client.on('connect', () => {
  console.log('Connected to broker');
  client.subscribe('test/topic', (err) => {
    if (!err) {
      client.publish('test/topic', 'Hello from Node.js MQTT client');
    }
  });
});

client.on('message', (topic, message) => {
  console.log(`Received message: ${message.toString()} on topic: ${topic}`);
});
Output
Connected to broker Received message: Hello from Node.js MQTT client on topic: test/topic
⚠️

Common Pitfalls

Common mistakes when implementing MQTT in Node.js include:

  • Not handling connection errors or waiting for the connect event before subscribing or publishing.
  • Forgetting to convert message buffers to strings when logging or processing.
  • Using incorrect topic names or not subscribing before publishing to receive messages.

Always listen for error events and confirm connection before sending messages.

javascript
/* Wrong way: publishing before connection */
const client = mqtt.connect('mqtt://broker.hivemq.com');
client.publish('test/topic', 'Message sent too early'); // May fail

/* Right way: wait for connect event */
client.on('connect', () => {
  client.publish('test/topic', 'Message sent after connect');
});
📊

Quick Reference

Remember these key points when using MQTT in Node.js:

  • Use mqtt.connect() to connect to the broker.
  • Subscribe to topics with client.subscribe() before expecting messages.
  • Publish messages with client.publish().
  • Handle connect and message events properly.
  • Convert message buffers to strings using message.toString().

Key Takeaways

Install and import the mqtt package to use MQTT in Node.js.
Always wait for the 'connect' event before subscribing or publishing.
Subscribe to topics to receive messages and use 'message' event to handle them.
Convert incoming message buffers to strings for readable output.
Handle errors and connection events to ensure reliable communication.