Can't connect to HiveMQ Cluster using React app + mqtt

Hi Hive team and community!

I found a lot of similar topics with the same issue, but after trying everything I found here and google, still I can’t connect to my cluster using a React app. The error is:

WebSocket connection to 'wss://b372c355b85c47dfa2d0e2633ec16662.s1.eu.hivemq.cloud:8884/mqtt' failed:

  • I am using wss:// and port 8884 with the sufix /mqtt
  • I checked if the connection is available using this command on mac:
    nc -zv b372c355b85c47dfa2d0e2633ec16662.s1.eu.hivemq.cloud 8884

what gives me:
Connection to b372c355b85c47dfa2d0e2633ec16662.s1.eu.hivemq.cloud port 8884 [tcp/*] succeeded!

My snippet:

import mqtt from 'mqtt'

const MyApp = () => {
  const [mqttClient, setMqttClient] = useState<mqtt.MqttClient>()
  const [mqttMessage, setMqttMessage] = useState('')

   useEffect(() => {
      const url = 'wss://b372c355b85c47dfa2d0e2633ec16662.s1.eu.hivemq.cloud:8884/mqtt'
      const options = {
        clientId: `mqttjs_${Math.random().toString(16).substring(2, 8)}`,
        username: 'my-user',
        password: 'my-pass'
      }

      const client = mqtt.connect(
        url,
        options
      )

      client.on('connect', () => {
        console.log('Connected to MQTT broker')
        // client.subscribe('my-topic')
      })

      client.on('message', (topic, payload) => {
        setMqttMessage(payload.toString())
      })

      client.on('error', (error) => {
        try {
          console.error('MQTT Error:', error)
        } catch (err) {
          console.error('Error in error handler:', err)
        }
      })

      setMqttClient(client)

    return () => {
      if (mqttClient) {
        mqttClient.end()
      }
    }
  }, [])

  return <></>
}

I can connect using Node JS app I am using on the backend with the same configs (changing the user/pass and clientId only) from the same machine and network too. Can you help me to understand what I am missing?

Thanks in advance!

Hello @dederomagnolo

I’m not very familiar with React code, but this improved example, based on your code, worked perfectly for me when connecting to my HiveMQ Cloud Serverless broker.

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

// For demonstration, remove StrictMode so that useEffect runs only once:
ReactDOM.createRoot(document.getElementById('root')).render(
  // <React.StrictMode>
    <App />
  // </React.StrictMode>
);

App.js

import React, { useEffect, useRef, useState } from 'react';
import mqtt from 'mqtt';

const App = () => {
  const clientRef = useRef(null);
  const [mqttMessage, setMqttMessage] = useState('');

  useEffect(() => {
    const url = 'wss://b372c355b85c47dfa2d0e2633ec16662.s1.eu.hivemq.cloud:8884/mqtt';
    const options = {
      clientId: `mqttjs_${Math.random().toString(16).substring(2, 8)}`,
      username: 'TYPE_USERNAME',
      password: 'TYPE_PASSWORD'
    };

    // Only create the client if it doesn't exist
    if (!clientRef.current) {
      const client = mqtt.connect(url, options);
      clientRef.current = client;

      client.on('connect', () => {
        console.log('Connected to MQTT broker');

        // Subscribe once connected
        client.subscribe('my-topic', (err) => {
          if (err) {
            console.error('Subscription error:', err);
          } else {
            console.log('Subscribed to my-topic');
          }
        });
      });

      client.on('message', (topic, payload) => {
        setMqttMessage(payload.toString());
      });

      client.on('error', (error) => {
        console.error('MQTT Error:', error);
      });
    }

    return () => {
      // Cleanup the client on unmount
      if (clientRef.current) {
        clientRef.current.end();
        clientRef.current = null;
      }
    };
  }, []);

  return (
    <div>
      <h1>MQTT Message:</h1>
      <p>{mqttMessage}</p>
    </div>
  );
};

export default App;

Kind regards,
Diego from HiveMQ Team

Hey Diego, thanks for your answer, I have some new too. I think there is something more blocking the access from my machine with mac os, cause I tested it in another machine (running windows) and I had success without changing my code! What is curious is that from my mac I can use a similar approach from the backend system. Any ideias what can cause this kind of connection from a browser running on mac? (I tested using Google Chrome)

Several factors might be blocking or interfering with the MQTT over WebSocket connection on macOS compared to Windows.

macOS may have a firewall setting or a third-party antivirus suite filtering WebSocket traffic.

Some Chrome extensions, such as ad-blockers, privacy tools, or corporate security extensions, can block WebSocket connections. Try disabling extensions or using an Incognito window to test if this resolves the issue.

Start by isolating these potential factors to identify the cause. Once identified, configuring the settings appropriately should enable the MQTT over the WebSocket connection to work as expected.

Kind regards,
Diego from HiveMQ Team