Node-RED and MQTT are the classic pairing for home automation: ESP32s and sensors publish to a Mosquitto broker, and Node-RED subscribes, processes, stores and displays the data, and sends commands back. This guide connects the two and gets a message flowing, then covers the parts you need for real projects: JSON payloads, wildcards, retained messages and dynamic topics.
Quick answer: drag an mqtt in node onto the canvas, add a new broker with Server set to the broker's IP (localhost if Mosquitto runs on the same Pi as Node-RED), Port 1883, and the username and password in the Security tab. Set the topic (wildcards such as home/# work) and wire it to a debug node. To publish, wire any node into an mqtt out node with a topic. Deploy: the node status shows a green connected dot when it works.
How the Pieces Fit
MQTT is publish/subscribe: a publisher sends a message to a named topic, the broker (Mosquitto) receives it, and forwards it to every client subscribed to that topic. Publishers and subscribers never talk directly, so devices can come and go without anyone being reconfigured.
In Node-RED:
- mqtt in subscribes to a topic and outputs one message per MQTT message received.
msg.topicis the topic,msg.payloadthe content. - mqtt out publishes
msg.payloadto the node's topic, or tomsg.topicif the node's topic is left empty. - Both share a broker configuration node, so you enter the server and login once.
Node-RED itself is not a broker. You need Mosquitto (or another broker) running; see installing Mosquitto on the Raspberry Pi.
1. Make Sure the Broker Is Reachable
| Where Mosquitto runs | Server to enter in Node-RED |
|---|---|
| Same Raspberry Pi or PC as Node-RED | localhost |
| Another computer on your network | That computer's IP, e.g. 192.168.1.20 |
| Docker container on the same host | The container name (same Docker network) or the host's IP; not localhost |
| A cloud broker | Its hostname, usually port 8883 with TLS |
Quick check on the broker:
systemctl is-active mosquitto # activeIf Node-RED is on a different machine, test the network path with mosquitto_sub -h 192.168.1.20 -t 'test/#' -u USER -P PASS -v from that machine. If that fails, Node-RED will fail too: see test MQTT without hardware.
2. Add the Broker in Node-RED
- Drag an mqtt in node onto the canvas and double-click it.
- Next to Server, choose Add new mqtt-broker and click the pencil.
- Connection tab: Server
localhost(or the broker IP), Port1883, Protocol MQTT V3.1.1 (or V5 if you need its features). Leave Client ID blank to let Node-RED generate a unique one. - Security tab: the broker username and password (create one with
mosquitto_passwd, for examplenodered). - Click Add, then Done, then Deploy.
Under the node, a green dot with connected means it works; a yellow connecting that never changes means Node-RED can't reach the broker (wrong IP or port, or the broker isn't listening on the network); a red disconnected often means a wrong login. The broker log says which: sudo journalctl -u mosquitto -f.
3. Publish and Subscribe: The First Test
Build two small flows on the same tab:
[inject: "Hello from Node-RED"] → [mqtt out: test/hello]
[mqtt in: test/#] → [debug]- inject: payload type string, value
Hello from Node-RED. - mqtt out: same broker, Topic
test/hello, QoS 0. - mqtt in: same broker, Topic
test/#, Output auto-detect. - debug: wired to the mqtt in node.
Deploy, click the inject button, and the Debug sidebar shows Hello from Node-RED with topic test/hello. The message went out to Mosquitto and back in. Topics are case-sensitive: test/Hello wouldn't match test/hello.
4. Receive Real Device Data (JSON)
Most ESP32 sketches publish JSON, such as {"temperature":22.4,"humidity":51} on home/livingroom/climate. Set the mqtt in node's Output to a parsed JSON object. msg.payload is then an object and you can use msg.payload.temperature directly, with no separate json node. (auto-detect also works when the payload is valid JSON.)
To send just the temperature to a gauge or database, add a change node: Set msg.payload to msg. payload.temperature.
Wildcards let one node cover many devices:
| mqtt in topic | Receives |
|---|---|
home/livingroom/climate | One device |
home/+/climate | Every room's climate sensor |
home/# | Everything under home |
With wildcards, msg.topic tells you which device sent each message, so a switch node can route by topic, or a function node can extract the room: msg.room = msg.topic.split("/")[1];. A sensible topic layout makes this easy; see MQTT topic naming best practices.
5. Send Commands to a Device
To switch something on an ESP32, publish to its command topic:
[inject: "ON"] ─┐
├→ [mqtt out: home/livingroom/lamp/set]
[inject: "OFF"] ─┘
[mqtt in: home/livingroom/lamp/state] → [debug]The device switches the lamp and publishes its real state to .../lamp/state, which you watch in Debug. On a dashboard, a switch widget does both jobs; the pattern is in Node-RED Dashboard 2.0, and the matching ESP32 code is in control an ESP32 LED with Node-RED and MQTT.
Dynamic topics. Leave the mqtt out node's Topic empty, and it publishes to whatever msg.topic each message carries, so one node can serve every device.
6. QoS and Retain in Node-RED
- QoS 0 (at most once) suits frequent sensor readings. QoS 1 (at least once) suits commands and status, where losing a message matters; duplicates are possible, so commands should be safe to repeat (
ON, notTOGGLE). QoS 2 is rarely needed at home. - Retain on the mqtt out node (or
msg.retain = true) stores the message on the broker for future subscribers. Use it for state and readings; leave it off for commands, which would otherwise replay at every reconnect. - An mqtt in node receives retained messages as soon as it connects, flagged with
msg.retain = true. Use that to tell a fresh reading from a stored one if it matters.
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| Node stuck on connecting | Can't reach the broker | Check the IP and port; Mosquitto 2.0 needs a listener 1883 line for network clients |
disconnected, log says not authorised | Wrong or missing login | Set the user and password in the broker node's Security tab |
| Connects, then drops every few seconds | Another client uses the same client ID | Leave Client ID blank, or make it unique |
| Connected but Debug stays empty | Topic mismatch, or nothing is publishing | Subscribe to # temporarily to see what arrives |
msg.payload is a string, not an object | Output set to a UTF-8 string | Set Output to a parsed JSON object |
| Old values appear when Node-RED starts | Retained messages | Expected; clear them with mosquitto_pub -t TOPIC -r -n if unwanted |
Works with localhost, not from Docker | localhost inside a container is the container | Use the host's IP or the broker container's name |
PubSubClient-style return codes and broker log lines are explained in MQTT troubleshooting.
Where to Take It Next
With MQTT flowing into Node-RED, the rest is building blocks:
- Dashboards: gauges, charts and switches in Node-RED Dashboard 2.0, or the finished ESP32 DHT11 and BMP280 dashboard.
- History: store readings in InfluxDB and chart them in Grafana: Node-RED, InfluxDB and Grafana.
- Automation: schedules, light-level rules and context in Node-RED automations.
- Alerts: motion to Telegram or email in Node-RED PIR alerts.
FAQ
Does Node-RED include an MQTT broker? No. The mqtt nodes are clients; you need Mosquitto or another broker. (Community nodes such as Aedes can run a small broker inside Node-RED, but Mosquitto is the more robust choice.)
What server address do I use? localhost if Mosquitto runs on the same machine as Node-RED; otherwise the broker's IP address.
Can one mqtt in node receive from many devices? Yes, with wildcards such as home/+/climate; msg.topic tells you the sender.
How do I publish JSON from Node-RED? Send an object as msg.payload to an mqtt out node; Node-RED converts it to a JSON string.
MQTT v3.1.1 or v5? v3.1.1 works with every device and library, including PubSubClient. Choose v5 only if you need its extra features, such as message expiry or user properties.
Summary
You connected Node-RED to Mosquitto, sent a message through the broker and back, parsed JSON from a device, used wildcards and dynamic topics, and learned when to use QoS 1 and retain. That's everything a Node-RED home-automation flow needs from MQTT; the rest is choosing what to do with the data.
Validate message shape before building automations
A flow that displays a value is not necessarily a flow that has validated it. MQTT payloads arrive as strings or buffers, and a JSON node can fail when a device publishes an empty, malformed or unexpected message. Add a validation step between the MQTT input and any dashboard, database or actuator. Confirm that the parsed message is an object, that required keys exist, and that numeric fields are actually finite numbers. Reject missing values rather than silently converting them to zero.
For example, a temperature message should be checked for a numeric temperature within a plausible range for the sensor and installation. A humidity value should be between 0 and 100 percent. These are application checks, not universal sensor limits: choose ranges that match the hardware and environment. If a payload fails validation, route it to a debug or error branch with the topic and reason, but avoid logging passwords or sensitive payloads.
Make the flow resilient
Use a Status node or the MQTT node's connection status to distinguish a disconnected broker from a quiet sensor. A quiet topic may mean the device is asleep, the publish interval is long, or the sensor read failed; it does not always mean the broker is down. Add a timestamp at the point the message is received, and if the device includes its own measurement timestamp, retain both. This helps identify stale readings and clock differences.
When sending commands back to a device, keep command and state topics separate. The dashboard should show the reported state, not merely the button press. For important actions, include a command identifier or sequence number and publish an acknowledgement from the device. That makes retries and duplicate delivery easier to reason about.
Finally, export a copy of the working Node-RED flow before changing node versions or credentials. Store secrets in Node-RED's credential mechanism or environment configuration rather than hard-coding them in Function nodes. Restrict the editor to trusted users and do not expose an unauthenticated Node-RED editor to the public internet.




