Table of Contents
MQTT.js MQTT client supports both Node.js and web browsers. It allows users to connect to a broker, publish messages, and subscribe to topics. The community that uses it is large and active. MQTT.js supports both CommonJS and ES6 systems and also supports MQTT over WebSockets in both the browser and in Node.js.
To get started with MQTT.js, first install Node.js.
Then install MQTT.js.
npm install mqtt
Then, create a client instance.
import mqtt from 'mqtt';
const client = mqtt.connect('mqtt://broker.hivemq.com');
Brokers are what make MQTT so efficient. Every device only needs to open one connection with a broker to share data with numerous other devies. HiveMQ’s MQTT broker can support up to 200 million connections. HiveMQ has a hosted option, HiveMQ Cloud Serverless, as well as an open-source option, HiveMQ CE.
A free HiveMQ Cloud account allows you to create two MQTT broker clusters and connect up to 100 devices. On the HiveMQ Cloud page, click ‘Try out for free’ button.
If you are accessing the HiveMQ Cloud portal for the first time, you must provide an email address and password and follow the simple steps to confirm your email and create your account.
An MQTT broker cluster will automatically be created when you complete your account setup. Establish your credentials to allow devices to connect to your MQTT broker.
You can do that by specifying the username and password and clicking on ADD.
If you wish to update your connection credentials, you can always log in to your portal, click ‘MANAGE CLUSTER,’ and select ‘ACCESS MANAGEMENT’.
To connect to HiveMQ with authentication you can use the following code to create a client instance.
If you want to use MQTT.js to make a WebSocket connection, you can also specify that when you create a client instance with the following code. const client = mqtt.connect(‘ws://hostname:8000’);
After connecting to a broker, you can begin publishing messages and subscribing to topics to share data between devices.
`client.publish('cluster/messages/node7', 'Hello, HiveMQ!');`
The code examples in this post come from The Ultimate Guide on How to Use MQTT with Node.js and there are many more examples there.
The following code is an example of implementing MQTT.js with security measures.
Using a client identifier, username, and password, also helps with security at the application level. Implementing these practices will help you take advantage of MQTT’s efficiency without compromising on the security of your data.
MQTT has a smaller message size and is more efficient for IoT use cases than HTTP and supports environments with limited network connection and many devices.
You can install MQTT.js in Node.js with the code