MQTT Client – Will topic and message retain

I was recently looking into implementing a MQTT client application where the server (and other clients) are notified when a client is disconnected. By definition the MQTT protocol supports such a feature through what is called a ‘will’ topic. When you create the client connection to the broker,  you also define the ‘will’ topic and a message that will be broadcasted by the broker to that topic, once the client has been disconnected.

As usual, I use Node.JS for quick prototyping IoT server-side apps. So I started typically with using the MQTT.js library, and thought of sharing with you the way to make a client connection and use the ‘will’ topic:

var server = 'mqtt://';

var mqtt = require('mqtt');

client = client = mqtt.connect(server, {
protocolId: 'MQIsdp',
protocolVersion: 3,
clientId: 'mqttjs'_ + crypto.randomBytes(16).toString('hex'),
will: {topic : "willtopic", payload: 'something happened here..'},
keepalive: 10


In addition, I wanted the mqtt clients to publish messages with the retain flag on (= when a new client is subscribed to a topic it receives all the previously published messages). Here is again how to do that:

client.publish('mytopic', 'mypayload', {retain: true});

Leave a Reply

Your email address will not be published. Required fields are marked *