Search code examples
node.jshttpswebsocketmqttmosca

Connect mqtt client via web sockets with HTTPS from browser


I would like to run a mqtt client on a web browser using web sockets with HTTPS. With HTTP, I have no problem. Here is the code on the web browser when using HTTP.

<script>
      var client  = mqtt.connect( 'wss://127.0.0.1:3000', {username:'test_user', password:'test_password'} );
      client.subscribe("mqtt/test");

      client.on("message", function(topic, payload) {
        alert([topic, payload].join(": "));
        client.end();
      });

      client.publish("mqtt/test", "testing hello world!");
</script> 

This is how I start the stand-alone mosca broker to use HTTPS on websockets.

mosca --very-verbose --key ./tls-key.pem --cert ./tls-cert.pem --credentials ./credentials.json --https-port 3000 --https-bundle --https-static ./ | pino

How should I change my mqtt client code on the browser to connect to the Mosca broker on websockets via HTTPS?


Solution

  • As discussed in the other questions you have asked, the web browser has it's own list of trusted CA certificates, your self signed certificate will not be in this list so the connection is going to fail.

    You can import your own trusted certs into your browser, but how to do this differs with each browser and you have to do it for EVERY instance of the browser so only really useful for individual testing.

    If you need to allow members of the public (or browsers you can't install your certificate on) to connect to your broker then you will have to get a certificate from a recognised CA. You will have to either pay for this or use a service like http://letsencrypt.org