Build your own Javascript MQTT Web Application

Why should I use Websockets with MQTT

With the new features introduced with HTML5 you can now even build websites which behave like a native desktop applications and work on tablets and smartphones the same way they do on a desktop computer. So using a browser like any app on any other mobile device is a very tempting idea. A browser is installed on nearly every desktop computer/laptop/tablet/smartphone around the world. And honestly wouldn’t it be nice if you could use one standardized protocol to get real push messages on all types of devices, browsers, tablets, smartphones, embedded devices, sensors, etc. The protocol you are looking for is MQTT and it is very simple and quick to implement.

How to use MQTT with websockets

For a simple websockets client which subscribes and publishes to a MQTT Broker, there are very few steps involved to get it up and running. It is actually pretty simple because there is a very good library available which already does most of the work for you, the Paho Javascript client.

To check that your code is working you can use the HiveMQ Websocket MQTT Client and publish/subscribe to the same topics as in the example code.

And if you don’t want to setup your own MQTT broker you can always use the public HiveMQ broker from the MQTT-Dashboard.


First of all we want set up a connection to the MQTT Broker. This is done by creating a Messaging.Client Object and calling the connect method with a set of options.


Subscribing to one or more topics is done by a simple call to the subscribe method of the client


Publishing to a specific topic requires you to create a Messaging.Message object and pass it to the publish method of the client


You can also check out the fullscreen demo or play with the JSFiddle.

Note: If you instantly see a few messages after you hit the subscribe button, these are so called retained messages. This means that the last message which has been sent to the broker for this topic which had the retained flag set will be persisted on the server and sent to every new subscriber to this topic. A pretty nice extra if you always want to have access to the last sensor reading that was published to the broker for example.

Additional Goodie

A very cool feature of MQTT is the ability to specify a so called Last-Will-And-Testament Message and Topic. Whenever a connection gets disconnected unexpectedly the broker will publish a message to a topic which was specified by the client on connect. In the websocket scenario this allows you to act on a closed tab/browser by reacting to the LWT message which was sent by the broker. You can set the LWT topic, message, etc. by passing additional properties in the options for the connect method.

P.S. The demo is available as one single html file here: hivemq_websocket_demo_app.html


  1. Martyn Eggleton says:

    Hi I’m trying the jsFiddle as I’m keen to let my students at school loose on MQTT and I’m getting this message when trying to connect “Connection failed: AMQJS0007E Socket error:undefined”. The forum isn’t loading for me and I’m a bit stuck. any thoughts?

  2. Hi Martyn,

    We did a short maintenance update on our public broker yesterday. So maybe that’s why it didn’t work. Can you please try again now.

    If it’s still not working, here is the link to the support forum:!forum/hivemq

    Hope that helps,

  3. Karthikeyan says:

    The demo available as single html file isn’t working even if I open directly on the browser. But it is working if I use the embedded one or from JS fiddle. I am new to JS. Please advise.

    Thank you!

    1. Hi Karthikeyan,

      it seems there has been an update to the Paho JS library and therefore our application is not working anymore. I have corrected the single html file to use the right library.

      We’ll update the code to the newest version shortly.

      Hope that helps,

  4. Gavin says:

    Hello,I connected the server correctly in the browser, but got a wrong ‘timed out’ in React Native. The wrong is ‘Object {invocationContext: undefined, errorCode: 1, errorMessage: “AMQJSC0001E Connect timed out.”}’.

    Thank you!

    1. Hi Gavin,

      we don’t have any experience with react-native. The error indicates that the connection could not be established to the HiveMQ broker. Can you share a Gist with the relevant code?

      Dominik from the HiveMQ Team

  5. Manish says:

    Is it true that PAHO js client has limited feture compared to paho java client. I can just see that we can set just 2-3 properties about message. How about knowing delivery confirmation ? message timestamp and other feaure that is supported by java client but cant see those thing in JS client docs.

    1. Hi Manish,

      the Paho Javascript library has a pretty solid and complete feature set, it supports all QoS levels. I’m not sure what you mean with the message timestamp. Have you seen the MQTT Client Library Encyclopedia Entry for Paho.js? It covers all features of the library, perhaps this will help? Check it out here:

      All the best,
      Dominik from the HiveMQ Team

  6. xinyu says:

    Hi I’m trying the jsFiddle to connect to the broker in the demo, but it not work, the error: “Connection failed: AMQJS0007E Socket error:undefined”

    1. Hi xinyu

      We did some maintenance on the public broker yesterday, it should work fine again

      Hope that helps,
      Christoph from the HiveMQ Team

  7. Sumit says:

    Is it possible to use 8883 port with this? If yes then how to do it?

    1. Hi Sumit,

      yes, it is possible to use port 8883.

      Just change the port you give to the constructor of Messaging.Client(hostname, port, clientid) to the port you want to use.

      Also you might have to run your own HiveMQ for this, since the public Broker listens on port 8000 only.
      For the configuration of HiveMQ see:

      Hope that helps,
      Christoph from the HiveMQ Team.

  8. Jarry says:

    Hi,my name is Jarry. Basically I facing some problem in the html button part. I wish to publish this command {“cmd”:”1″} but however it highlighted the commands and when i press publish, there is no reaction.

    <button onclick="publish('{cmd:1}’,’ESPert/14366266/LED’,2);”>3. Publish3

    I even try the above method, it success to come out the command that I want but in my MQTT, it pop out {cmd:1} which is the things I don’t want. May I know how to solve it?

  9. R says:

    MQTT key advantage is that it is a lightweight protocol. Does using MQTT over WebSockets introduce extra overhead to the broker (and communication)?

    1. Hi there,

      the overload caused by WebSockets is minimal and can be neglected in most use cases.

      Florian, from The HiveMQ Team.

  10. vivek says:

    I am new to android java platform and i want to make an android app which can access data from the mqtt broker and display it in the mobile.
    Taking topic as input from user

  11. Suhaimi says:

    Is there any way to change the host name? I would like to use my own server, set up on my linux computer.

    Really appreciate your help. thank you.
    Have a good day!

    1. Hi Suhaimi,

      You can change the hostname on the first line of the JavaScript, when the MQTT client is created.
      var client = new Messaging.Client("", 8000, "myclientid_" + parseInt(Math.random() * 100, 10));
      To use your own server, replace the hostname “” and the host-port “8000” accordingly.

      Kind regards,
      Florian from The HiveMQ Team.

  12. Aaron says:

    Hello, my company is developing an app to manage a physical device over MQTT, and we are having disconnect issues where wifi is being dropped and then reconnected, the device however then reports the socket is busy, would implementing the LWT resolve this issue?

    1. Hi Aaron,

      nice to see you are taking an interest in MQTT and HiveMQ.
      From the given information my guess would be you are having some sort of half open socket connection problem caused by the unstable WiFi.
      This is just a guess on my end tho, as we have seen similar behaviour in the past. The LWT features does not have any impact on this kind of problems.
      You’re welcome to contact for further investigation, as this would exceed the scope of a blog post comment.

      Best regards,
      Florian, from The HiveMQ Team.

  13. Nagaraj says:

    Can you please give me syntax how to integrate the MQTT in angular js projects . I am getting the following error ”ws://’ failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET”

    1. Hi Negaraj,

      Nice to see you are taking an interest in MQTT and HiveMQ.
      Did you try connecting to ws:// ?
      For problems with Eclipse IoT please refer to the respective support.

      Thank you and kind regards,

  14. Dear Sir,
    How do I set the Flow In MQTT Broker In Node-Red and How to get Websocket port 8000

  15. Kool Engineer says:

    Hi, I wanna know that how can I connect to MQTT Broker with username and password. I am new to java script and I wanted to know how can I modify this line of code to implement username and password authentication var client = new Messaging.Client(hostname, port, clientid);

    Thanks in advance 🙂

    1. Hi,

      You can pass username and password as options to the connect method.

      You can take a look at the code from the Websocket Client to see how this is done.

  16. João says:


    I build a POC using your public online broker and PAHO Javascript Client and it was working perfectly until last Friday (30/03/2018).

    At the moment the client can’t connect to the broker and it’s returning the following error message: “Connection failed: AMQJS0007E Socket error:undefined”.

    Since I did not change the code, what do you think can be causing this issue?


    1. Hello João,

      Nice to see you’re taking an interest in MQTT and HiveMQ.

      The public HiveMQ broker is meant for testing purposes only and does not provide any availability guarantees.
      When it gets unavailable, it usually takes circa 2 business hours (Monday through Friday 10:00 – 18:00 CEST) for it to go back up.
      You can download HiveMQ and run it locally. This way you can test HiveMQ in a controlled environment.

      Kind regards,
      Abdullah from the HiveMQ Team.

Leave a Reply

Your email address will not be published. Required fields are marked *