MQTT.js in Browser - LWT Formatting in JS?

I’ve been testing HiveMQ by connecting to the public web-sockets enabled broker at ws:// using MQTT.js in the browser. I’m able to correctly send things over except for the LWT section.

What is the correct way to format the option packet sent with: mqtt.connect(url, options) in the browser version of MQTT.js?
Specifically it seems I’m having trouble formatting the “payload” of the will:

For testing this is just pulling values from input boxes in HTML:

    clientId: client_id_input.value,
    username: user_input.value,
    password: password_input.value,
    will: {topic: lwt_topic_input.value,
          //  payload: lwt_message_input.value
          //  payload: Buffer.from(utf_encoder.encode(lwt_message_input.value)), 
           qos: lwt_qos_input.value as mqtt.QoS

MQTT.js is supposed to offer TS types included in the file, but the types seem to have a problem currently with the bowser version. The Node version expects a “Buffer” type for payload, which is not available in the browser.

Or should I give up and use the Paho.js library? I had hesitated to use this as the Github repo appear abandoned, with no updates in years (or maybe that just shows it is stable.)

In the browser version of MQTT.js, does the “payload” need to somehow be converted manually to something other than a string? client.publish does not need any conversion, so I don’t know why the LWT payload would.

I’ve tried to cheat and use the Node.js typings, and they are somewhat helpful but like I mentioned it incorrectly shows needing a Buffer type in the will payload, and without the browser version types I’m not sure what should go here.


Hi, @davemays

And a warm welcome to the HiveMQ Community! We’re excited that you’re interested in MQTT and the HiveMQ broker. Your presence adds value to our community.

You can manually convert your LWT payload to a Uint8Array, which can be used in the browser. In MQTT.js for the browser, you can convert a string to a Uint8Array like this:

const payload = new TextEncoder().encode(lwt_message_input.value);

Ultimately, your choice between MQTT.js and Paho.js depends on your preferences and project requirements. If you find Paho.js more suitable for your needs or easier to work with, there’s no harm in using it, even if the repository hasn’t seen recent updates.

I hope this helps!

Dasha from HiveMQ Team