Search code examples
node.jsmqttmosquitto

Get mqtt message header in node.js server with mosquitto broker


How to get header agent or device/browser details in mqtt message with mosquitto broker. My mqtt code sample:

var mqtt = require('mqtt');
var client  = mqtt.connect('mqtt://127.0.0.1:1883',{
   username: 'xxxx',
   password: 'xxxx'
});
client.on('connect', function (err,done) {
    if(err){
        console.log(err)
    }else{
        console.log("Connected...")
        client.subscribe('test');
    }
})
client.on('message', function (topic, message) {
    // want to get the header details here.
})

Solution

  • You can not get anything other than the message payload and topic from a MQTT message because no other information is included in the message format. This is by design, in Pub/Sub messaging the only thing that matters in the topic and the payload, not who sent it.

    The on('message',function(){}) callback can take a 3rd parameter which is the raw mqtt-packet object. You can see full list of data available in the doc here. But the only extra information is about duplicate status, qos and if the message is retained.

    client.on('message',function(topic, message, mqtt-packet) {
    ...
    });
    

    If you need more information you need to manually include it in the message payload published by the client yourself.