Connections from multiple Browsers to Mosquitto MQTT via Web Sockets not Working

If you are using the paho javascript MQTT client library to connect to MQTT via web sockets, you might notice that you can’t connect from multiple browser sessions at the same time. This may be because you are using the same client ID for each connection – you should use a different client ID for each connection.

client = new Paho.MQTT.Client('192.168.1.123', 9001, 'some-client-id');  // Doesn't work

To get around this you could generate a random client Id like this:

client = new Paho.MQTT.Client('192.168.1.123', 9001, Math.random().toString());

This generates a thoroughly meaningless/ugly client Id, but it works…

There is some worry that using an approach like this can lead to a buildup of stale sessions on the server side as the browser will pass a completely different client Id on each connection/refresh but I am not sure, I think this may only affect persistent sessions, will keep an eye on it…