---
title: Intro to Event-Driven Node.js with MQTT
description: Use MQTT to manage your smart devices at a large scale. Learn about how MQTT works and implement an MQTT broker with Aedes on Node.js in this post!
image: https://www.bitovi.com/hubfs/Intro%20to%20Event-Driven%20Node.js%20with%20MQTT.png
---

- ![AI implementation](https://www.bitovi.com/hubfs/AIConsultingIcon.svg)
  
  [AI implementation](https://www.bitovi.com/services/ai-consulting)
- ![Systems engineering](https://www.bitovi.com/hubfs/icon%20-%20backend.svg)
  
  [Systems engineering](https://www.bitovi.com/services/systems-engineering-consulting)
- ![Project Management](https://www.bitovi.com/hubfs/icon%20-%20PM.svg)
  
  [Project Management](https://www.bitovi.com/services/agile-project-management-consulting)
- ![Product Design](https://www.bitovi.com/hubfs/icon%20-%20design.svg)
  
  [Product Design](https://www.bitovi.com/services/product-design-consulting)
- ![Frontend development](https://www.bitovi.com/hubfs/icon%20-%20frontend.svg)
  
  [Frontend development](https://www.bitovi.com/services/frontend-development-consulting)
- [View more
  
  →
  
  ](https://www.bitovi.com/digital-consulting-services)

We're Experts in...

- [JavaScript](https://www.bitovi.com/services/frontend/javascript-consulting)
- [AI training](https://www.bitovi.com/ai-training-for-software-engineers)
- [Angular](https://www.bitovi.com/services/frontend/angular-consulting)
- [Design systems](https://www.bitovi.com/services/axure-figma-migration)
- [React](https://www.bitovi.com/services/frontend/react-consulting)
- [Temporal](https://www.bitovi.com/services/backend/temporal-consulting)
- [React Native](https://www.bitovi.com/services/frontend/react-consulting/react-native)
- [Node.js](https://www.bitovi.com/services/backend/nodejs-consulting)

Showcase

![Yum! Brands](https://www.bitovi.com/hubfs/yum-showcase-link-1.png)

[View case study](https://www.bitovi.com/en/bitovi-yum-case-study)

More Projects

- [![Levi's](https://www.bitovi.com/hubfs/levis.svg)](https://www.bitovi.com/web-application-consulting-work/levis-ecommerce-responsive-redesign)
- [![Christie's International Real Estate](https://www.bitovi.com/hubfs/christies.svg)](https://design.bitovi.com/christies)
- [![BAFS](https://www.bitovi.com/hubfs/bafs.svg)](https://www.bitovi.com/ux-design-consulting/ux-case-studies/bafs-ppp)
- [View more
  
  →
  
  ](https://www.bitovi.com/our-software-consulting-work)

Open Source Tools

We build powerful tools and open source them to support the community.

[See what we've built →](https://www.bitovi.com/open-source)

- [![Blog](https://www.bitovi.com/hubfs/icon%20-%20blog.svg)
  
  BlogWe post about delivering products and solving problems.
  
  ](https://www.bitovi.com/blog)
- [![Partnerships](https://www.bitovi.com/hubfs/Handshake-1.svg)
  
  PartnershipsLearn about Bitovi's technology partners
  
  ](https://www.bitovi.com/partnerships)
- [![Academy](https://www.bitovi.com/hubfs/icon%20-%20academy%20(4).svg)
  
  AcademyFree courses to build delivery skills
  
  ](https://www.bitovi.com/academy)
- [![Open source tools](https://www.bitovi.com/hubfs/icon%20-%20open%20source.svg)
  
  Open source toolsUse or contribute to our community
  
  ](https://www.bitovi.com/open-source)

Let's Connect

- [![Discord](https://www.bitovi.com/hubfs/DiscordLogo.svg)
  
  Discord
  
  ](https://discord.gg/J7ejFsZnJ4)
- [![LinkedIn](https://www.bitovi.com/hubfs/LinkedinLogo.svg)
  
  LinkedIn
  
  ](https://www.linkedin.com/company/bitovi/)
- [![GitHub](https://www.bitovi.com/hubfs/GithubLogo.svg)
  
  GitHub
  
  ](https://github.com/bitovi/)

![Eggbot](https://www.bitovi.com/hubfs/build_assets/bitovi-limbo-cms-react/338/js_client_assets/assets/eggbot-LTGhdSGL.png)

Name *

Work Email *

Phone

What's your project?

Send

### Contact Us

(312) 620-0386contact@bitovi.com

 August 5, 2022

# Intro to Event-Driven Node.js with MQTT

 Use MQTT to manage your smart devices at a large scale. Learn about how MQTT works and implement an MQTT broker with Aedes on Node.js in this post!

![Eric Schow](https://www.bitovi.com/hubfs/avatar_600.jpg)

 Eric Schow

Share:

[![Twitter](https://www.bitovi.com/hubfs/limbo-generated/_astro/twitter-white.os3xLc3C_Z2nW4or.svg) ](https://twitter.com/intent/tweet?text=) [![Reddit](https://www.bitovi.com/hubfs/limbo-generated/imgs/icons/reddit.png) ](http://reddit.com/submit?url=)

The "Internet of Things" is growing larger than ever. Manufacturers continue to develop more "smart" household appliances with features like control via smartphone, smart speaker integrations, and automatic updates pushed from a central server.

This connectivity requires a robust messaging protocol like MQTT. In this blog post, we'll cover everything you need to know about MQTT and how to implement it in your applications. 

## What is MQTT?

MQTT is a lightweight, low-bandwidth, binary protocol designed by IBM in the 1990s. It operates on a publish-subscribe model—a client publishes a message on a given “topic” and the connected broker routes the message to clients who have subscribed to the same topic.

### Publish-Subscribe vs Message Queue

One common misconception about MQTT is that it's a message queue protocol. In a message queue, if a client publishes a message and no subscriber is around to hear it, the broker keeps that message in a queue until a subscriber comes online to get it.

In a publish-subscribe model like MQTT, if a client misses a message, it’s gone forever. (At least, without using some advanced features of the protocol.) 

## Basic Concepts in MQTT

Let’s take a look at some core concepts of MQTT—Topics, Wildcards, and how they work with the publish-subscribe model.

### Topics

Topics are strings that the broker uses to filter messages for each client. They're broken up into topic levels separated by forward slashes.

Example topics might include:

- `home/appliances/kettle/temperature`
- `usa/texas/houston`
- `store123/device456/status`

Each level of a topic should get more specific as you move further inwards. The broker uses specificity to route messages more efficiently, as well as enable a more powerful feature: Wildcards.

### Wildcards

Here's an example system to help explain Wildcards. Imagine a warehouse filled with hundreds of smart devices, with each device publishing several different kinds of information:

- Picker robots might publish their position every few seconds, and also publish an event when interacting with objects.
- Thermometers in the cold storage area might publish the ambient temperature.
- A sorting machine might have broken down and published an error event to a general error topic for the building.

The above messages could be sent on the following topics:

- `warehouse001/zone3/picker01/location`
- `warehouse001/zone3/picker01/status`
- `warehouse001/zone4/thermostat01/temperature`
- `warehouse001/zone4/thermostat01/status`
- `warehouse001/error`

Notice that, apart from the error topic, the topic schema is divided into four sections, each getting more specific:

- Warehouse
- Zone
- Machine ID
- Message type

Now imagine a programmer implementing a system to view the different messages published by `picker01` in `zone3`. Perhaps the full collection of potential messages is unknown; maybe a `picker` software version upgrade in the future results in an additional publish whenever a `picker` has an `interaction` with a warehouse item.

To solve that problem, the `picker01` management software can simply subscribe to `warehouse001/zone3/picker01/+` . This results in receiving  `warehouse001/zone3/picker01/location`, `warehouse001/zone3/picker01/status` as well as a hypothetical `warehouse001/zone3/picker01/interaction` all at once.

The `+` character represents a single-level wildcard. It replaces one portion of a topic, and signals to the broker to route all messages that match the wild-carded topic to the subscriber. The `+` does not need to go at the end, however. For example, if the manager of `zone3` wanted the `status` of each device, a subscription to `warehouse001/zone3/+/status` would result in receiving messages from `picker01`, as well as any other devices in `zone3`.

There is also an even more powerful wildcard available: the multi-level wildcard, indicated by `#`. A logging system for `warehouse001` that needs to receive every message that any device publishes could simply subscribe to `warehouse001/#` and receive every message for that warehouse.

Now that we know how topics and wildcards work, let’s review how they work together with publish and subscribe.

### Publish and Subscribe

With MQTT, there are only two types of devices involved in the system: a single broker and multiple clients. Clients can subscribe to topics and wildcards. They can also publish messages to specific topics.

Published messages are then received by other clients which are subscribed to the message or a matching wildcard. The broker’s job is to route the messages from publishing clients to subscribed clients.

Clients connect to a broker similarly to how web apps connect to a server—a TLS connection is made to a machine that has an app listening on a specific port.

With most servers the client requests work to be done by the server itself; however, with MQTT the broker itself does no work apart from relaying messages.

Here is a visualization of the publish-subscribe system:

![Image showing MQTT subscribe and publish model](https://www.bitovi.com/hs-fs/hubfs/MQTT1.png?width=678&name=MQTT1.png)

## Visualize & Learn with MQTT Box

Now it's time to implement what you've learned with hands-on example! First, you'll need an MQTT broker. For this example, you'll use the `aedes` package [from npm](https://www.npmjs.com/package/aedes) to create and run a broker. Then you’ll use a Google Chrome extension to visualize how publish and subscribe work.

### Run the MQTT Broker

Running an MQTT broker is as straightforward as these few lines of code:

```
const aedes = require("aedes")();
const server = require("net").createServer(aedes.handle);
const port = 1883;

server.listen(port, function () {
  console.log("server started and listening on port ", port);
});

aedes.on('publish', function({topic, payload}) {
  console.log("broker routing published message", topic, payload?.toString());
});
```

We’ve already prepared [an example project on Github](https://github.com/bitovi/mqtt-intro) for you to clone and try it out. Once you’ve cloned the repo, run `npm install` then `npm start` in the project’s root folder to start the broker.

### Visualize with MQTT Box

With the broker running, the next step is to connect to it using an MQTT client. You can use the [MQTT Box Chrome App](https://chrome.google.com/webstore/detail/mqttbox/kaajoficamnjijhkeomgfljpicifbkaf/related) to subscribe to and publish messages.

### Create an MQTT Client

Once you've installed and opened MQTT Box, you should see the option to create an MQTT client. If not, navigate to "Clients" in the menu. Click the "Create MQTT Client" button:

![how to create an MQTT client](https://www.bitovi.com/hs-fs/hubfs/create-mqtt-client.png?width=694&name=create-mqtt-client.png)

 

You'll be presented with the below form for creating a client. There are three values that need to be filled in:

- MQTT Client Name: `Client` (or any value, really)
- Protocol: `mqtt/tcp` (we didn't enable other options)
- Host: `localhost:1883` (to match the port on the server)

Don't forget to click save!

![how to select client settings and payload](https://www.bitovi.com/hs-fs/hubfs/mqtt-3.png?width=694&name=mqtt-3.png)

### Subscribe and Publish

Once you've created an MQTT client, you'll see a pane on the left titled "Topic to publish" and a pane on the right called "Topic to subscribe"

![MQTT-4](https://www.bitovi.com/hs-fs/hubfs/MQTT-4.png?width=694&name=MQTT-4.png)

You *could* fill in the topic on the publish side and start publishing, but you won't see anything happen after you subscribe. To witness the UI changing, you first need to create a subscriber.

Fill in the topic on the subscriber and press the "Subscribe" button. Now you can fill in the payload field on the publish side and hit "Publish". And voila! The UI for the Subscriber will update with the message contents:

![how to create a publish and subscribe system with MQTT](https://www.bitovi.com/hs-fs/hubfs/MQTT-5.png?width=694&name=MQTT-5.png)

You can create as many publishers and subscribers as you wish in the MQTT box app and watch them update as you subscribe to and send messages. Maybe try some wildcards based on what we reviewed, earlier.

## Summary

Now that you know about the core concepts of MQTT and have a working broker set up on your machine, you’re well on your way to becoming an Internet of Things developer.

In the next post on MQTT, we’ll focus on converting our demo broker into a more real-world service: a home automation controller!

### Need help implementing MQTT?

Bitovi has expert backend web development consultants ready to help with your project! Schedule a [free consultation](https://www.bitovi.com/nodejs) to get started. 

 

  

[![Tag for node.js](https://www.bitovi.com/hubfs/limbo/icons/tag.svg) node.js ](https://www.bitovi.com/blog/topic/node-js)[![Tag for nodejs consulting](https://www.bitovi.com/hubfs/limbo/icons/tag.svg) nodejs consulting ](https://www.bitovi.com/blog/topic/nodejs-consulting)[![Tag for mqtt](https://www.bitovi.com/hubfs/limbo/icons/tag.svg) mqtt ](https://www.bitovi.com/blog/topic/mqtt)

 Previous Post

![Bitovi ESLint Config: Handpicked Rules to Improve Your Code](https://www.bitovi.com/hs-fs/hubfs/Bitovi%20ESLint%20Config-%20Handpicked%20Rules%20to%20Improve%20Your%20Code.png?height=117&name=Bitovi%20ESLint%20Config-%20Handpicked%20Rules%20to%20Improve%20Your%20Code.png) [ Bitovi ESLint Config: Handpicked Rules to Improve Your Code ](https://www.bitovi.com/blog/bitovi-eslint-config-handpicked-rules-to-improve-your-code)

  

 Next Post

![How to Create a Path Alias in Webpack](https://www.bitovi.com/hs-fs/hubfs/How%20to%20Create%20a%20Path%20Alias%20in%20Webpack.png?height=117&name=How%20to%20Create%20a%20Path%20Alias%20in%20Webpack.png) [ How to Create a Path Alias in Webpack ](https://www.bitovi.com/blog/how-to-create-a-path-alias-in-webpack)

```json
{
  "@context" : "http://schema.org",
  "@type" : "Organization",
  "address" : {
    "@type" : "PostalAddress",
    "addressCountry" : "United States",
    "addressLocality" : "Libertyville",
    "addressRegion" : "IL",
    "postalCode" : "60048",
    "streetAddress" : "1134 Pine Tree Lane "
  },
  "alternateName" : "Bitovi",
  "areaServed" : {
    "@type" : "GeoCircle",
    "geoMidpoint" : {
      "@type" : "GeoCoordinates",
      "latitude" : "41.8781",
      "longitude" : "87.6298"
    },
    "geoRadius" : "5000 km"
  },
  "description" : "Bitovi is a UX, UI design and front-end JavaScript development consulting company",
  "email" : "contact@bitovi.com",
  "image" : "https://www.bitovi.com/hubfs/bitovi-logo-x2.png",
  "logo" : "https://www.bitovi.com/hubfs/bitovi-logo-23-1.svg",
  "mainEntityOfPage" : {
    "@id" : "https://www.bitovi.com/blog/intro-to-event-driven-node.js-with-mqtt",
    "@type" : "WebPage",
    "description" : "Use MQTT to manage your smart devices at a large scale. Learn about how MQTT works and implement an MQTT broker with Aedes on Node.js in this post!"
  },
  "naics" : "541511",
  "name" : "Bitovi Web App Consulting",
  "sameAs" : [ "https://www.facebook.com/BitoviLLC/", "https://twitter.com/bitovi", "https://www.linkedin.com/company/bitovi" ],
  "telephone" : "312-620-0386",
  "url" : "http://bitovi.com"
}
```

```json
{
  "@context" : "http://schema.org",
  "@type" : "BlogPosting",
  "author" : {
    "@type" : "Person",
    "name" : "Eric Schow"
  },
  "dateModified" : "September 29, 2023, 7:56:57 PM",
  "datePublished" : "2022-08-05 14:00:00",
  "description" : "Use MQTT to manage your smart devices at a large scale. Learn about how MQTT works and implement an MQTT broker with Aedes on Node.js in this post!",
  "headline" : "Intro to Event-Driven Node.js with MQTT",
  "image" : {
    "@type" : "ImageObject",
    "url" : "https://www.bitovi.com/hubfs/Intro%20to%20Event-Driven%20Node.js%20with%20MQTT.png"
  },
  "publisher" : {
    "@type" : "Organization",
    "logo" : {
      "@type" : "ImageObject",
      "url" : "https://www.bitovi.com/hubfs/bitovi-logo-23-1.svg"
    },
    "name" : "Bitovi"
  }
}
```