This project demonstrates MQTT pub/sub messaging using TypeScript.
sequenceDiagram
participant P as Publisher
participant B as Mosquitto Broker
participant S as Subscriber
S->>B: CONNECT
B-->>S: CONNACK
S->>B: SUBSCRIBE (topic: nodejs-mqtt-sample/demo)
B-->>S: SUBACK
P->>B: CONNECT
B-->>P: CONNACK
loop Every 3 seconds
P->>B: PUBLISH (sensor data)
B->>S: Forward message
end
P->>B: DISCONNECT
S->>B: DISCONNECT
MQTT (Message Queuing Telemetry Transport) is a lightweight publish/subscribe messaging protocol designed for constrained devices and low-bandwidth networks. It's widely used in IoT, home automation, and real-time data pipelines.
Core concepts:
- Broker — a central server that receives all messages from publishers and routes them to the appropriate subscribers. Clients never talk directly to each other.
- Topic — a UTF-8 string that acts as a routing channel (e.g.
sensors/temperature). Topics support hierarchical wildcards (+for single level,#for multi-level). - Publish — a client sends a message to a topic. The broker then forwards it to every client subscribed to that topic.
- Subscribe — a client registers interest in one or more topics. It will receive all future messages published to those topics.
- QoS (Quality of Service) — controls delivery guarantees:
0— At most once (fire and forget)1— At least once (acknowledged delivery, possible duplicates)2— Exactly once (four-part handshake, no duplicates)
- Retained messages — the broker stores the last message on a topic so new subscribers immediately get the latest value.
- Last Will and Testament (LWT) — a message the broker publishes on behalf of a client if it disconnects unexpectedly.
Why MQTT over HTTP?
| MQTT | HTTP | |
|---|---|---|
| Connection | Persistent (single TCP connection) | Request/response per call |
| Direction | Bidirectional push | Client-initiated pull |
| Overhead | 2-byte minimum header | Headers on every request |
| Pattern | Pub/Sub (decoupled) | Point-to-point |
| Best for | Real-time streams, IoT, events | REST APIs, document transfer |
- Publisher — connects to the MQTT broker and sends simulated sensor data (temperature + humidity) every 3 seconds.
- Subscriber — connects to the same broker, subscribes to the topic, and logs incoming messages.
- Broker — Eclipse Mosquitto 2 running locally in Docker.
- Node.js 18+
- pnpm
- Docker & Docker Compose
pnpm installStart the MQTT broker:
docker compose up -dOpen two terminals:
Terminal 1 — Subscriber:
pnpm run dev:subscriberTerminal 2 — Publisher:
pnpm run dev:publisherYou'll see the subscriber receive messages published by the publisher in real time.
pnpm run build
pnpm run start:subscriber # terminal 1
pnpm run start:publisher # terminal 2Edit src/config.ts to change the broker URL, topic, QoS level, or client IDs.
The default broker is localhost:1883 via Docker Compose.