How to Subscribe to a Topic Using MQTT Protocol
To subscribe to a topic using
mqtt, use the subscribe() method on your MQTT client instance with the topic name as the argument. This tells the client to listen for messages published to that topic and receive them automatically.Syntax
The basic syntax to subscribe to a topic in MQTT is:
client.subscribe(topic, options, callback)
Where:
topicis the name of the topic to subscribe to (string).optionsis an optional object to set subscription options like QoS.callbackis an optional function called when the subscription is acknowledged.
javascript
client.subscribe('topic/name', { qos: 0 }, function (err, granted) { if (!err) { console.log('Subscribed to topic:', granted[0].topic); } });
Example
This example shows how to connect to an MQTT broker and subscribe to a topic named home/temperature. It prints any messages received on that topic.
javascript
const mqtt = require('mqtt'); const client = mqtt.connect('mqtt://broker.hivemq.com'); client.on('connect', () => { client.subscribe('home/temperature', { qos: 1 }, (err, granted) => { if (err) { console.error('Subscription error:', err); } else { console.log('Subscribed to:', granted[0].topic); } }); }); client.on('message', (topic, message) => { console.log(`Message received on ${topic}: ${message.toString()}`); });
Output
Subscribed to: home/temperature
Message received on home/temperature: 22.5
Common Pitfalls
- Not waiting for the
connectevent before subscribing causes errors because the client is not ready. - Using incorrect topic names or wildcards can prevent receiving messages.
- Ignoring the callback error can hide subscription failures.
- Not handling the
messageevent means you won't receive messages even if subscribed.
javascript
/* Wrong: subscribing before connection */ client.subscribe('topic/name'); /* Right: subscribe after connection */ client.on('connect', () => { client.subscribe('topic/name'); });
Quick Reference
Remember these key points when subscribing to MQTT topics:
- Always subscribe after the client connects.
- Use correct topic names and QoS levels.
- Handle errors in subscription callbacks.
- Listen for
messageevents to receive data.
Key Takeaways
Subscribe to MQTT topics only after the client is connected.
Use the subscribe() method with the topic name and optional QoS.
Handle subscription errors in the callback function.
Listen for message events to receive published messages.
Use correct topic names to ensure you receive the intended messages.