0

I'm using MQTT.JS in a React component. For some reason when I try to connect to my HiveMQ host the connect function prepends the URL with "localhost"

Does anyone have an idea why this is happening?

First I called the connect function with an option object which contained a "host" key. The result was that the connect function ignored the host key and connected to ws://localhost directly

const mqttConnect = (mqttOptions) => {
    console.log(JSON.stringify(mqttOptions, null, 4))
    setClient(mqtt.connect( mqttOptions ))
}

The second thing I tried was to call the function naming the host explicitly by including it as the first argument. That resulted in the connect function prepending the host URL with ws://localhost

const mqttConnect = (mqttOptions) => {
    console.log(JSON.stringify(mqttOptions, null, 4))
    setClient(mqtt.connect( mqttOptions.host, mqttOptions) )
}

This is what the options object looks like:

mqttOptions: { "host": "58xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx0c.s1.eu.hivemq.cloud", "port": "8884", "clientId": "icodefusion", "username": "icode", "password": "password", "protocol": "MQTT" }

I included a snapshot of the error https://imagizer.imageshack.com/img923/3495/UEAqem.jpg

Blue Robin
  • 847
  • 2
  • 11
  • 31
icode gfx
  • 1
  • 1

2 Answers2

0

The protocol key should come from the output of URL.parse() so should contain wss not MQTT for a MQTT over websockets.

I believe you have miss read the doc which mentions protocolId

hardillb
  • 54,545
  • 11
  • 67
  • 105
0

Based on the config you are showing, this should be the correct way to call the connect function:

const mqttConnect = ({host, clientId, username, password}) => {
  setClient(mqtt.connect(`wss://${host}`, {clientId, username, password}))
}

See https://www.npmjs.com/package/mqtt#api for details.

Christian Fritz
  • 20,641
  • 3
  • 42
  • 71
  • Thank you for the responses, the results were a little better but for some reason the connect function still wants to connect to 'localhost'. Here is a snapshot of the state of my component/client and the options followed by the error: https://imagizer.imageshack.com/img924/9287/CoNmBA.jpg – icode gfx Feb 17 '23 at 03:59