Customizing your own MQTT Broker with Node Js
In today’s world, MQTT protocol is being used in a wide range of industries ranging from manufacturing to telecommunications and smart home automations. Sharing an image from the official site :
As you already know, one of the main components of an MQTT setup is a broker which acts as an interface/channel between the publisher and subscriber of data. There are many free mqtt brokers available which you can use. Although other mqtt brokers like Mosquitto provided a great authentication mechanism, they were pretty straight forward. My main motive to setup a custom mqtt broker for my project was to implement a custom authentication mechanism where each user would have a separate set of credentials and metadata attached with it which I could also use to authorize the user before publishing or subscribing to any topic.
The prerequisite for this post is having the basic understanding of how MQTT works and its basic terminology. If you’re new to MQTT , I would highly recommend you to read HiveMQ’s MQTT Essentials.
Things being said, let’s get started.
I will be using Aedes for creating a mqtt server. It’s a javascript library provided by MoscaJs having many extensions and plugins which can be used additionally to create a more customized and efficient implementation based on your requirements.
Create a folder named Mqtt-Broker (or anything else) and run npm init -y
in it’s terminal to instantly initialize your project with default values. Now add the required dependencies to your project by running the following command :
npm i --save aedes net
The npm package net
is used to create the server using aedes. Now create a file src/index.js and paste the following code in it —
You can also configure your aedes server using many options like message queue limit, persistence for storing messages and subscriptions for QoS>0, heartbeat interval, connection timeout etc.
Start your server by running the command npm start
.
Voilà !! Your mqtt broker is up and running. But that’s not it. Aedes API provides us with two important objects : aedes
and client
, which we can use to our needs to handle the various events which are triggered in the broker and also to perform operations such as authentication and authorization on clients.
Few of the common events triggered on the broker are :-
client
: when a client connects to the broker.clientDisconnect
: when a client disconnects from the broker.subscribe
: when a client subscribes to a message topic on the broker.unsubscribe
: when a client unsubscribes from a message topic on the broker.publish
: when a client publishes a message-packet.
… and many more. The aedes
object also has many handler functions such as authenticate
(authenticating the client), authorizePublish
(authorizing a client to publish message on a topic), authorizeSubscribe
(authorizing a client to subscribe to a message topic) etc.
On the other hand, the client
object provides you the access to all the important properties of the client such as id
, clean
, connected
, connecting
etc. It also provide methods to perform certain tasks such as publish
( publishing a message packet on a topic), subscribe
(subscribing the client to a set of message topics), close
(disconnects a client) etc.
Let’s see them in action…!!
Add the following methods in your index.js :
In the above code snippet, I have used the authenticate
handler function to authenticate client credentials. If the client’s username and password are ‘username’ and ‘password’ respectively, the connection b/w the client and the broker is established successfully, else the broker throws an error of authentication failed and the connection is discarded. Similarly, we use the authorizePublish
handler function to authorize a producer client whether or not it can publish the message packet on the topic based on a given condition. You can also use the authorizeSubscribe
handler to authorize a client whether it can subscribe to a given message topic or not.
Below are some of the events triggered on the broker server on interactions with a client. Add these in your index.js file :-
The above code snippet explains itself and the events can be used according to the project requirements. For instance , if you plan to incorporate persistent-storage in your broker, you would want to :
- add a client’s subscription in the storage on ‘subscribe’ event
- remove a client’s subscription from the storage on ‘unsubscribe’ event
- store a message packet on ‘publish’ event … etc
The aedes library uses an in-built persistence mechanism using aedes-persistence to store the client’s subscription and topic messages for QoS > 0. Therefore, you won’t need to worry about the messages published on the topic not getting delivered to the client which was offline/disconnected for a short period of time, given that the previous connection of the client was established with cleanSession = false and client had previously subscribed to the topic with QoS > 0.
To sum up the code, your index.js might look something like this :
Now, to manually test the broker, make sure your server is up and running, then try connecting your mqtt client to the broker. You may use Mqtt.fx , a free and easy java based client which can be used for testing the broker.
Below is a sample video showing the broker logs on interaction with the mqtt client.
Allowing systems to run on low bandwidth and low power, mqtt is now being used widely in the smart home automation process. It’s light, easy to understand and scalable. You may also run a cluster of brokers for load balancing.
This brings us to an end of this blog..!! Feel free to raise any query and i’ll be happy to answer them. Do like and share if you liked the content ! 😄