Creating a MQTT client using Javascript for NodeJS and browser

Recently I came across this requirement where I had to implement a MQTT client using Javascript for NodeJS and browser. It is easier than you think it is using the npm mqtt package . Latest release till date is 1.11.2 but if you run into any errors while using browserify on the created client, then I advice switching back to 1.8 version because of a dependency issue with the dependency mqtt-packet . Install the mqtt dependency using

npm install mqtt --save

You could then require the module as shown below.

var mqtt    = require('mqtt');

Create a simple client passing in the MqttOptions object. Information on the properties has been given on the git hub page but it is very basic. If you’re someone new to MQTT, you’re better off reading the explanation provided in HiveMQ essentials series.

Create a simple MqttOptions as shown below passing in the basic parameters.

var mqttOptions = {
clientId: 'f1b948b7-2114-4c8e-962f-d15f4cf90abe',
protocolId: 'MQTT',
protocolVersion: 4,
keepalive: 10000,
clean: false,
reconnectPeriod: '1000',
will: willMessage

The above would require a will message object which would be used to notify connected clients about another disgracefully disconnected client. Creating it would be done as follows.

var willMessage = {
topic: 'WillMessage',
payload: 'This is the last will message',
qos: 2,
retain: true

Use the above created MqttOptions object to establish the connection to the Mosquitto broker.

var client = mqtt.connect("mqtt//:localhost:1883", mqttOptions);

URL could be one of  ‘mqtt’, ‘mqtts’, ‘tcp’, ‘tls’, ‘ws’, or ‘wss’. I’ll cover establishing secure connection methods in the up coming tutorials.

Once the connection has been established you can publish and subscribe to messages as shown below.



You could also hook onto the following callbacks and implement logic accordingly.

  • connect – function(connack) {}
  • reconnect – function() {}
  • close – function() {}
  • offline – function() {}
  • error- function(error) {}
  • message – (topic, message, packet) {}
  • packetsend – function(packet) {}
  • packetreceive – function(packet) {}

Below is an example implementation of the connect call back mentioned above.


client.on('connect', function () {

console.log('client connected');


client.on('message', function (topic, message) {



Auto reconnect when failing to connect to the server has already been implemented through the library and you could see this by hooking onto the ‘reconnect’ method. I have come across an abnormal behavior where the previously subscribed topics have been lost after successfully connecting on a reconnect, though I have set clean property in MqttOptions object to false. Check whether you encounter this issue and if so, keep track of the subscribed topics in a list and subscribe to them again in the reconnect callback.

You could terminate the client using client.disconnect method.

I hope that would have given a clear idea as to how to create a MQTT client using Javascript for NodeJS. You could use browserify to create a version of the file that could be used in browsers. As I mentioned at the start of this post, if you encounter an errors while browserifying the file, always switch back to the 1.8 version in which it works fine.

So I’ll wind up this post for here now. I’ll add another post on how to establish ssl/tls and wss connections through the clients! 🙂


Getting started with MQTT and Mosquitto

What it is and why you would need it

If you’re looking for a light weight messaging protocol then MQTT would an answer you could consider. It follows the publish-subscribe mechanism but of course you could tweak it to suit one-one messaging as well. MQTT has been quite a trending topic these days with the evolution of the Internet of Things. Objectives of this protocol is to have high reliability through assurance of delivery while playing with minimum network bandwidth. Clear evidence of this being achievable through the protocol has been visible through the usage of it in IOT where sensors, mobile devices and embedded computers use it for messaging purposes.

Recently I came across the need for a messaging bus where we first came up with the implementation of our own messaging bus. This had taken about 5-7 milliseconds for end-to-end delivery of messages. Later on we came across MQTT and it took only one millisecond for end-to-end delivery of messages. It could also support websocket connections which helped us remove our own implementation of a websocket client from the project as well. FAQ page of MQTT would provide you with answers for most of the questions that would’ve risen in you by now!

Mosquitto – The messaging broker

The messaging broker we had used is Mosquitto which is an open source project from Eclipse that implements the MQTT protocols 3.1 and 3.1.1.

You could download the latest version of Mosquitto from here . Simply run the mosquitto executable from the downloaded folder and you’re good to go. You could enable verbose logging with the -v parameter and configurations could be loaded from a specific file through the usage of -c parameter. Read more about the configurations from here . Running the mosquitto executable would create a non-secure connection through the default port 1883 and secure encrypted connections could network connections and authentications could be established through SSL. Download the latest version of open SSL and copy the libeay32.dll, ssleay32.dll and libssl32.dll files to your mosquitto installation folder. Apart from that, download the pthreadvc2.dll and place that in the mosquitto installation folder as well.

In order to configure the server for certificate authentication, follow these steps and generate a certificate authority certificate and key, server key and a server certificate by creating a CSR and signing it with your CA key. Place the below entries into the configuration file and restart the mosquitto broker.

listener 8883
cafile certs/ca.crt
certfile certs/server.crt
keyfile certs/server.key
require_certificate true

Default port 8883 has been used in this scenario and setting the require_certificate to true would require the client to provide a valid certificate in order to establish the connection. This could be set to false if clients are not expected to be authenticated through their certificates.

Websocket support also needs to be explicitly enabled. This requires libwebsockets and a step by step instruction set on how to achieve this could be found here . You could also enable SSL authentication through websockets and a sample configuration would look like shown below.

listener 9002
protocol websockets
cafile certs/ca.crt
certfile certs/server.crt
keyfile certs/server.key
require_certificate true

That’s it and you have setup your mosquitto with additional websocket and SSL support!

MQTT could be the answer for any of your requirements of a lightweight messaging protocol even if it doesn’t involve IOT just like in my case! Hope this would’ve given an idea of what MQTT is and how to setup Eclipse’s Mosquitto broker. Soon I’ll follow this up with tutorials on create clients using Java and NodeJS. Happy messaging folks! 🙂