Skip to content

Paho JavaScript - MQTT Client Library Encyclopedia

by James Sutton
6 min read

The Eclipse Paho project provides a number of open-source clients of the MQTT and MQTT-SN messaging protocols. The Paho JavaScript client is a browser based library that takes advantage of WebSockets to connect to an MQTT Broker. The Library was originally authored by Andrew Banks at IBM and was donated to Eclipse by IBM in 2013.

Overview of Paho JavaScript MQTT Client Library

Paho JavaScript
Language JavaScript
License Eclipse Public Licence
Website http://www.eclipse.org/paho/
API Style Asynchronous

The library is considered to be very stable and is used in many MQTT-based web applications. It’s also available to use via a GUI on the Eclipse Paho website as well as HiveMQ’s very own Websocket-Client. By using WebSockets, the JavaScript library allows developers to take advantage of MQTT without having to worry about port 1883 being blocked, they can simply point it at a WebSocket enabled MQTT Broker on port 80 and they are ready to go.

Features Supported by Paho JavaScript MQTT Client Library

Feature
MQTT 3.1 Yes
MQTT 3.1.1 Yes
LWT Yes
SSL/TLS Yes
Automatic Reconnect No

Advanced Features Supported by Paho JavaScript MQTT Client Library

Features Yes
QoS 0 Yes
QoS 1 Yes
QoS 2 Yes
Authentication Yes
Throttling No

Usage

Installation of Paho JavaScript MQTT Client Library

The JavaScript Paho library is available as a download from the project page and is all that is required to use it in your project. Once downloaded, simply include it in your HTML file using the script tags:

<script src="mqttws31.js">
</script>

How to Connect Paho JavaScript MQTT Client Library to an MQTT Broker?

Connecting to a broker is relatively simple with the JavaScript client, a basic example is shown below.

// Create a client instance: Broker, Port, Websocket Path, Client ID
client = new Paho.MQTT.Client("iot.eclipse.org", Number(80), "/ws", "clientId");

// set callback handlers
client.onConnectionLost = function (responseObject) {
    console.log("Connection Lost: "+responseObject.errorMessage);
}

client.onMessageArrived = function (message) {
  console.log("Message Arrived: "+message.payloadString);
}

// Called when the connection is made
function onConnect(){
	console.log(“Connected!”);
}

// Connect the client, providing an onConnect callback
client.connect({
	onSuccess: onConnect
});

Connect with MQTT 3.1 or MQTT 3.1.1

By default, the standard action is to connect using MQTT 3.1.1, however if that fails, you could fall back and try to connect as MQTT 3.1. This is managed from the connectOptions object.

3 - MQTT 3.1 4 – MQTT 3.1.1

// Connect the client, using MQTT 3.1
client.connect({
	onSuccess: onConnect, 
	mqttVersion: 3
});

Connect with LWT

In order to use the really handy Last-Will-and-Testament feature of MQTT, we can use the same options object as in previous examples.

// Connect the client, with a Last-Will-and-Testament
var lwt = new Paho.MQTT.Message(“payload”);
lwt.destinationName = “topic”;
lwt.qos = 0;
lwt.retained = false;

client.connect({
	onSuccess: onConnect, 
	willMessage = lwt
});

Connect with Username/Password

The JavaScript client can also authenticate using a Username and Password.

// Connect the client, with a Username and Password
client.connect({
	onSuccess: onConnect, 
	userName : “Username”,
	password : “password”
});

How to Publish an MQTT Message Using Paho JavaScript?

Once you are connected to the MQTT broker, you are able to publish a message. This is fairly straight forward and can be done as such:

// Publish a Message
var message = new Paho.MQTT.Message(“Message Payload”);
message.destinationName = “topic”;
message.qos = 0;

client.send(message);

Although destinationName is required, and QoS is optional. If not supplied, QoS will default to 0.

How to Publish A Retained Message?

Publishing a retained message is very simple too, just set retained to true.

// Publish a Message
var message = new Paho.MQTT.Message(“Message Payload”);
message.destinationName = “topic”;
message.retained = true;

How to Subscribe to An MQTT Message Using Paho JavaScript

Subscribing to a topic can be done with this one liner:

client.subscribe(“topic”);

When a message arrives, the onMessageArrived Callback will be called with a MQTT Message object. You can use it like this:

client.onMessageArrived = function (message) {
  console.log("Message Arrived: " + message.payloadString);
  console.log(“Topic:     “ + message.destinationName);
  console.log(“QoS:       “ + message.qos);
  console.log(“Retained:  “ + message.retained);
  // Read Only, set if message might be a duplicate sent from broker
  console.log(“Duplicate: “ + message.duplicate);
}

You can also set more advanced options when subscribing:

client.onMessageArrived = function (message) {
  console.log("Message Arrived: " + message.payloadString);
  console.log(“Topic:     “ + message.destinationName);
  console.log(“QoS:       “ + message.qos);
  console.log(“Retained:  “ + message.retained);
  // Read Only, set if message might be a duplicate sent from broker
  console.log(“Duplicate: “ + message.duplicate);
}

How to Unsubscribe to An MQTT Message Using Paho JavaScript

Unsubscribing is equally as simple as subscribing:

client.unsubscribe(“topic”);

You can also set more advanced options when unsubscribing:

var unsubscribeOptions = {
	invocationContext: {foo: true},  // Passed to success / failure callback
	onSuccess: onSuccessCallback,
	onFailure: onFailureCallback,
	timeout: 10
};
client.unsubscribe (“topic”, unsubscribeOptions);

How to Disconnect?

Disconnecting is done like this:

client.disconnect();

Using SSL/TLS

Connecting to your broker using TLS is also very straight forward. Make sure that you’ve set the port to your Brokers TLS / WebSocket port, then set the useSSL setting in the connectOptions:

// Connect the client, with a Username and Password
client.connect({
	onSuccess: onConnect, 
	useSSL: true
});

Keep in mind that as the browser manages external connections, you may receive an error in the console if the Certificate is not trusted.

Example Application of Using Paho JavaScript

Below is a very simple JavaScript application that will subscribe to the topic /World, the publish the Message 'Hello' to it.

// Create a client instance
client = new Paho.MQTT.Client(location.hostname, Number(location.port), "clientId");

// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;

// connect the client
client.connect({onSuccess:onConnect});

// called when the client connects
function onConnect() {
  // Once a connection has been made, make a subscription and send a message.
  console.log("onConnect");
  client.subscribe("/World");
  message = new Paho.MQTT.Message("Hello");
  message.destinationName = "/World";
  client.send(message); 
}

// called when the client loses its connection
function onConnectionLost(responseObject) {
  if (responseObject.errorCode !== 0) {
    console.log("onConnectionLost:"+responseObject.errorMessage);
  }
}

// called when a message arrives
function onMessageArrived(message) {
  console.log("onMessageArrived:"+message.payloadString);
}

Thanks for this guest blog post by James Sutton | IBM

James Sutton

James works for IBM in the Internet of Things Foundation team. He is a contributor on the Eclipse Paho Project, mainly working on the Java, Android and JavaScript Clients

Related content:

HiveMQ logo
Review HiveMQ on G2