Search code examples
mqttmqtt.js

`userProperties` is not found on mqtt.js subscriber client


I'm implementing MQTT publisher and subscriber using MQTT.js. And I'm using HiveMQ Cloud as a broker.

When I sent packet with user property by the publisher, I expected my subscriber to receive the packet with user property, but it didn't.

Here's my code. First one is the publisher, and the next one is the subscriber.

import { connect } from "mqtt";

const connectOptions = {
  host: 'hive cloud',
  port: 8883,
  protocol: 'mqtts',
  username: 'username',
  password: 'password'
}
let client = connect(connectOptions)

client.on("connect", (connack) => {
  console.log("client connected", connack);
})

setInterval(() => {
  const payload = {1: "Hello world", 3: "Welcome to the test connection"}
  const publishOption = {
    qos: 1,
    retain: false,
    properties: {
      userProperties: {
        user: 'property'
      }
    }
  }
  client.publish('test/connection708', JSON.stringify(payload), publishOption)
}, 5000)

.

import { connect } from "mqtt";

const connectOptions = {
  host: 'hive cloud',
  port: 8883,
  protocol: 'mqtts',
  username: 'username',
  password: 'password'
}

const topicName = 'test/connection708'

export let client = connect(connectOptions)

client.on('connect', (connack) => {
    console.log(connack)
    client.subscribe(topicName, (err, granted) => {
        if (err) {
            console.log(err, 'err')
        }
        console.log(granted, 'granted')
    })
})

client.on('message', (topic, message, packet) => {
    console.log(packet, message.toString())
})

The packet I got through subscriber was same as down here:

Packet { cmd: 'publish', retain: false, qos: 0, dup: false, length: 76, topic: 'test/connection708', payload: <Buffer 7b 22 31 22 3a 22 48 65 6c 6c 6f 20 77 6f 72 6c 64 22 2c 22 33 22 3a 22 57 65 6c 63 6f 6d 65 20 74 6f 20 74 68 65 20 74 65 73 74 20 63 6f 6e 6e 65 63 ... 6 more bytes> }

And the packet payload was {"1":"Hello world","3":"Welcome to the test connection"}

The subscriber successfully received packet and its payload, but I couldn't find the user property I gave, which is the object {user: 'property'}.

HiveMQ supports MQTT v5. But Just in case, I tried with local HiveMQ broker, but it didn't work.


Solution

  • You will need to explicitly tell the client to connect using MQTT v5, to use MQTT v5 features, since by default it will use protocolVersion 4 (which it 3.1).

    const connectOptions = {
      host: 'hive cloud',
      port: 8883,
      protocol: 'mqtts',
      username: 'username',
      password: 'password',
      protocolVersion: 5
    }