This project is a Proof of Concept of a basic MQTT broker and client implementation in NodeJS/Typescript. MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol commonly used in IoT (Internet of Things) applications.
I am using Aedes as a messaging broker and MQTT.js as client.
This implementation supports:
- all in one solution
- insecure connections
- username/password authentication
- TLS connections
- Log Level Based Logging
- customizable event handlers
- client can act as both, subscriber and publisher
npm i --save @m-reiniger/node-mqtt
Install Dependencies:
npm install
Build:
npm run build
Run Broker:
npm run broker
Rum Subscriber Client:
npm run subscriber
Run Publisher Client:
npm run publisher
const options = {
port: 8883,
auth: {
useAuth: true,
username: 'user',
password: 'pass'
},
tls: {
useTLS: true,
key: '--- your key file contents here ---',
cert: '--- your cert file contents here ---'
}
}
import { MQTTBroker } from "@m-reiniger/node-mqtt";
// create broker
const broker = new MQTTBroker(options);
// start broker server
broker.start();
const options = {
port: 8883,
host: 'localhost'
auth: {
useAuth: true,
username: 'user',
password: 'pass'
},
tls: {
useTLS: true,
key: '--- your key file contents here ---',
cert: '--- your cert file contents here ---'
}
}
import { MQTTClient } from "@m-reiniger/node-mqtt";
// create client
const client = new MQTTClient(options);
// connect to broker
client.connect();
client.subscribe('my/topic', (topic: string, message: Buffer) => {
console.log(`received "${message.toString()}" on topic ${topic}`);
// your code here
});
client.publish('my/topic', 'my message');
See an example usage implementation in src/example.ts.
See API Docs.
In order to use TLS you need to create key and cert files first. You can use the provided cert/*.pem
files for testing purposes, BUT I HIGHLY RECOMMEND to create your own.
To create a TLS/OpenSSL certificate for secure communication, you can follow the instructions provided in the link: How to create TLS/OpenSSL Cert. This guide will walk you through the process of setting up a certificate for local HTTPS development.