cannot connect to “mqtt://” from React client

I want to connect a client React app to the mosquitto test server. The “meat” React code involved:

import mqtt from 'mqtt';

    const mqttConnect = ("mqtt://",{clientId:"mqttjs01"}) => {
        setClient(mqtt.connect(host, mqttOptions));

The error on the web page is:

ws.js:108 WebSocket connection to 'ws://' failed: 

so one challenge I see is the insistence of a web socket. (ws protocol). Then another challenge is my ultimate goal is to talk to a mosquitto broker running on a Raspberry Pi (port 1883, which I thought the mqqt:// was addressing). The Raspberry Pi is not using websockets.

It appears clear to me that I am clueless. Any guidance / pointing in the right direction…greatly appreciated. Thank you.

With React you have to use WebSockets (because it effectively runs in the broswers) so your URL should start with ws:// not mqtt://.

Secondly you need to specify a port because there is no default port for MQTT over Websockets (and the WebSockets library will default to port 80)

So having checked the table of port numbers on you should be using:


p.s your client id’s also probably need to have a lot more entropy (be random) otherwise you’ll only ever have 1 connected client.

As for your local setup, you will need to configure mosquitto to listen on 2 different ports:

  • One for normal MQTT (default 1883)
  • One for MQTT over WebSockets (any port you want)

e.g. a conf file something like:

allow_anonymous true

listener 1883

listener 9001
protocol websockets

Mosquitto will share the same topic space between both listeners.

Read more here: Source link