Skip to content

Tutorial

Node-RED 8-Channel Relay Dashboard with MQTT State Feedback

Control eight relays from a Node-RED Dashboard 2.0 page over MQTT, with switches that follow the board's reported state, an online indicator, All off and fixes.

  • 4 min read
  • Updated November 2, 2026
Node-RED 8-Channel Relay Dashboard with MQTT State Feedback

Quick answer: for an 8-relay Node-RED dashboard, add eight ui-switch widgets (Dashboard 2.0) with on/off values ON / OFF and Passthrough turned off. Send each switch's output through one function node that builds the topic solderhub/lab/relaybox01/command/channel/N to an mqtt out node (not retained). Feed the switches from an mqtt in node on …/state/channel/+, so each switch shows what the relay board reports, not what you clicked. Add the board's …/status topic as an online/offline indicator and an All off button. The firmware side is in ESP32 8-channel relay over MQTT; both guides use the same topics.

The most common bug in relay dashboards is a feedback loop: the state message updates the switch, the switch re-sends a command, the board answers with state again… Turning Passthrough off breaks the loop, and driving the switches from the reported state means the dashboard can never show a relay as ON when the board didn't switch it.

You needNotes
Node-RED 3.x or 4.xInstall on a Pi or on Windows
@flowfuse/node-red-dashboard (Dashboard 2.0)The old node-red-dashboard is deprecated
Mosquitto brokerInstall Mosquitto
ESP32 + 8-channel relay board running the matching sketchESP32 relay firmware

1. The topic contract

TopicPublished byPayloadRetained
solderhub/lab/relaybox01/command/channel/1 … /8Node-REDON / OFFNo
solderhub/lab/relaybox01/command/allNode-RED (All off button)OFFNo
solderhub/lab/relaybox01/state/channel/1 … /8ESP32ON / OFFYes
solderhub/lab/relaybox01/statusESP32 / broker Last Willonline / offlineYes

Commands must never be retained: a retained ON is replayed every time the board reconnects. Use explicit ON/OFF rather than TOGGLE, so a duplicated or retried message can't flip a relay the wrong way.

2. Build the dashboard (8 switches)

  1. Manage palette → Install @flowfuse/node-red-dashboard.
  2. Create a page (/relays) and a group (Relay box 01).
  3. Add eight ui-switch nodes in that group. For each one:
ui-switch settingValue
LabelA real name, e.g. Workshop light, Fan, Pump
On payload / Off payloadstring ON / string OFF
PassthroughOff (prevents the command → state → command loop)
TopicThe channel number: 1 … 8 (or set msg.topic with a Change node after the switch)
  1. Add a ui-button All off with payload OFF and topic all.
  2. Add a ui-text Relay box for the online/offline status.

Name the switches after the load, not "Relay 3". Keep a written channel-to-load list next to the board too.

3. Wire the flow

Commands: all 8 switches and the All off button → function "to command topic" → mqtt out (broker set, topic empty, QoS 1, retain false).

script.js
// function "to command topic": builds .../command/channel/N or .../command/all
const BASE = "solderhub/lab/relaybox01/command/";
const payload = String(msg.payload).toUpperCase();
if (payload !== "ON" && payload !== "OFF") {
  node.warn("Rejected payload: " + msg.payload);
  return null;
}
if (msg.topic === "all") {
  if (payload !== "OFF") return null;          // "all" only ever switches OFF
  return { topic: BASE + "all", payload: "OFF" };
}
const ch = Number(msg.topic);
if (!Number.isInteger(ch) || ch < 1 || ch > 8) {
  node.warn("Rejected channel: " + msg.topic);
  return null;
}
return { topic: BASE + "channel/" + ch, payload: payload };

State back to the switches: mqtt in on solderhub/lab/relaybox01/state/channel/+ (output: a String) → function "route state" with 8 outputs → output N wired to switch N:

script.js
// function "route state": 8 outputs, one per ui-switch
const ch = Number(msg.topic.split("/").pop());
if (!Number.isInteger(ch) || ch < 1 || ch > 8) return null;
if (msg.payload !== "ON" && msg.payload !== "OFF") return null;
const out = new Array(8).fill(null);
out[ch - 1] = { payload: msg.payload };
return out;

Because the state topics are retained, opening the dashboard (or restarting Node-RED) immediately shows all eight real states.

Online/offline: mqtt in on solderhub/lab/relaybox01/status → ui-text. The ESP32's Last Will publishes offline if it loses power, so you know when switches can't do anything. Optionally colour it with a Change node or a ui-template.

4. What happens in each situation

SituationWhat the user sees
Tap Fan ON, board onlineSwitch moves, relay clicks, state ON confirms it (well under a second on a LAN)
Tap Fan ON, board offlineStatus shows offline; the switch jumps back when the next state message arrives, or stays where the last report left it after a refresh
Board rebootsAll switches go OFF (the board boots OFF and republishes state)
Node-RED restartsSwitches restore from the retained state topics
Two phones openBoth stay in sync, since both follow the reported state

Useful extras

Auto-off timer for a channel

Pumps, heaters and irrigation valves should never stay on forever because someone forgot. Add a trigger node on the state of that channel:

  1. mqtt in on solderhub/lab/relaybox01/state/channel/4 → switch node: payload == ON (output 1), == OFF (output 2).
  2. Output 1 → trigger node: send nothing, then wait for 10 minutes, then send payload OFF, with extend delay if new message arrives off. Output 2 → the same trigger node with msg.reset = true set by a Change node, so turning it off by hand cancels the timer.
  3. Trigger output → change node setting msg.topic to 4 → the same to command topic function.

Because the timer watches the reported state, it also covers channel 4 being switched on from Home Assistant, a schedule or another phone. For something safety-critical, put the maximum run time in the ESP32 firmware too, so it still applies when Node-RED is down.

Show when each relay last changed

In the route state function, add a ninth output that sends { payload: "Ch " + ch + " " + msg.payload + " at " + new Date().toLocaleTimeString() } to a ui-text or a ui-table log. That small line answers "who switched the pump on at 3 a.m.?" surprisingly often.

Confirm before switching dangerous loads

For a heater or a gate, add an Arm switch next to it. Store its value with a Change node in flow.armed4, and in the to command topic function reject ON for that channel unless flow.get("armed4") is true, then reset the flag after one use. Two taps are a small price for not opening the garage by accident.

Group and label clearly

Use one Dashboard group per room or per relay box, put the online/offline text at the top of each group, and keep labels identical to the physical labels on the relay board's enclosure. Clear naming prevents more mistakes than any amount of code.

5. Test before connecting real loads

Use LEDs or a 12 V lamp on the relay contacts while testing.

  1. Watch the broker: mosquitto_sub -h <broker> -u <user> -P '<pass>' -t 'solderhub/lab/relaybox01/#' -v.
  2. Toggle each switch and confirm one command/channel/N message and one state/channel/N reply, with no repeats (a repeating pair means Passthrough is on).
  3. Press All off: eight OFF states arrive.
  4. Unplug the ESP32: status changes to offline within about 20 seconds.
  5. Restart Node-RED: switches come back showing the real states.
  6. Check the broker has no retained commands: mosquitto_sub -t 'solderhub/lab/relaybox01/command/#' -v -W 2 should print nothing.

Protect the dashboard and broker before using it beyond the bench: httpNodeAuth for the dashboard, MQTT users and ACLs, and no port forwarding. See Secure Node-RED.

Troubleshooting

SymptomLikely causeFix
Relays flicker or MQTT floods with messagesPassthrough on, so state messages re-emit commandsTurn Passthrough off on every ui-switch
Switch moves but nothing is publishedTopic not set, so the function rejects the channelSet the switch Topic to 1–8; check the debug sidebar warning
Switch jumps back after tappingBoard didn't apply the command (offline, wrong topic)Check status, topic spelling and the ESP32 Serial Monitor
Wrong relay switchesSwitch topic doesn't match the physical channelFix the Topic numbers or the board's pin order
Relays switch on after a reconnectA retained command is stored on the brokerClear it: mosquitto_pub -t '…/command/channel/N' -r -n
Switches show OFF after Node-RED restartState not retained by the boardFirmware must publish state with retain = true
Status never shows offlineBoard doesn't set a Last WillUse the LWT in the firmware's connect() call
Dashboard 404Old /ui URLDashboard 2.0 lives at /dashboard

FAQ

Why not use a single JSON command for all eight relays? You can, e.g. {"ch":3,"state":"ON"} on one topic. Per-channel topics are easier to secure with ACLs, easier to watch with mosquitto_sub, and map directly to Home Assistant MQTT switches.

Can I control the same relays from Home Assistant too? Yes. Because everyone follows the retained state topics, Node-RED, Home Assistant and phones all stay in sync.

Can I add schedules? Yes: an Inject node at a set time sending {topic: "3", payload: "ON"} into the same function. See Node-RED scheduler and context.

Is a dashboard switch safe for mains equipment? Only as a convenience. Use rated relays in an enclosure, fusing and a local manual off; a dashboard is not an emergency stop.

Continue learning

Related articles

All articles

Signal In

Built from what makers search for

The lookups piling up in SolderHub's search bar every day shape what we publish next — new component pages, board guides, and firmware notes, sent out as they go live.

By subscribing you agree to our Privacy Policy. Unsubscribe anytime.