Search code examples
reactjsmqtthivemq

How to connect HiveMqtt to React app using mqtt package


I am trying to connect my react application to HiveMQ using mqtt.js package but I am having this error.

Screenshot of the error

This is the code I used

useEffect(() => {
        const options: IClientOptions = {
          protocol: "ws",
          username: "myfirstdevice",
          password: "qweqwe123",
        };

        const client = mqtt.connect('ws://8dedd20fc1164c8e9ce132a8a8359991.s1.eu.hivemq.cloud:8884', options);
        // const client = mqtt.connect(options);
        client.on('connect', function () {
            console.log('Connected');
        });
        client.on('error', function (error) {
            console.log("ERROR", error);
        });
        client.on('message', (topic,message,packet)=>{
            console.log("RECEIVE", topic)
            console.log("RECEIVE", message)
            console.log("RECEIVE", packet)
        });
      }, []);

Solution

  • Port 8884 is for MQTT over Secure WebSockets

    You'll need to change the URL to start with wss:// not ws://