Quick answer: a reliable Node-RED flow does four things. It validates every incoming message. It packages repeated logic into a subflow (select the nodes → Selection to Subflow), with per-instance settings read via env.get(). It splits a big canvas into sections joined by Link In / Link Out / Link Call nodes. And it routes failures to a Catch node, which receives msg.error, plus Status and watchdog nodes so a silent device or broker drop gets noticed. Add bounded retries (never infinite) and tested backups, and the flow survives bad data, outages and restarts.
| Tool | Solves | Where |
|---|---|---|
| Subflow | Same logic copied onto many flows | Menu → Subflows → Selection to Subflow |
Subflow properties + env.get() | Each copy needs its own settings | Subflow template → Properties tab |
| Link In / Link Out | Long crossing wires, flows split across tabs | Common palette |
| Link Call | Reusable "function call" that returns a result | Common palette (Node-RED 3.0+) |
| Catch | Errors thrown by nodes disappearing silently | Common palette |
| Status | Noticing MQTT/serial disconnects | Common palette |
| Trigger (watchdog) | A device that just stops sending | Function palette |
| Persistent context | Counters and state lost on restart | contextStorage in settings.js |
1. Turn repeated logic into a subflow
If you have pasted the same validate-and-format nodes onto three sensor flows, a fix now needs three edits. A subflow holds the logic once; every instance updates when you edit the template.
- Select the nodes that repeat (for example json → validate → change).
- Menu → Subflows → Selection to Subflow. Node-RED replaces them with one subflow node and keeps the wires.
- Double-click the subflow instance → Edit subflow template to open it on its own tab.
- On the template's Properties tab, add settings that differ per use, for example
MIN(number),MAX(number) andLABEL(string). Each instance then gets its own values in its edit dialog. - Inside the subflow, read them with
env.get("MIN")in a Function node, or choose env variable in any typed input such as a Switch or Change node.
A reusable range-check subflow (one input, two outputs: valid, rejected):
// Function node inside the subflow, Outputs: 2
const min = Number(env.get("MIN"));
const max = Number(env.get("MAX"));
const v = Number(msg.payload);
if (!Number.isFinite(v) || v < min || v > max) {
msg.reason = env.get("LABEL") + ": out of range (" + msg.payload + ")";
return [null, msg]; // output 2: rejected
}
msg.payload = v;
return [msg, null]; // output 1: validAn unset property returns an empty string "", not undefined, so convert and check it. Add a Status node inside the subflow (send it {fill:"green", shape:"dot", text:"ok"}) to show a status under each instance on the main canvas.
Keep subflows to one responsibility ("validate a reading", "send an alert"), and name them by what they do.
2. Untangle the canvas with Link nodes
Link Out → Link In pairs are invisible wires: a message entering the Link Out appears at every Link In it's connected to, even on another tab. Use them to split a big flow into readable areas such as Inputs, Logic, Outputs and Errors, and put each area in a group with a clear name.
Link Call (Node-RED 3.0 and later) works like calling a function: it sends the message to a Link In, the target section processes it, and a Link Out set to "Return to calling link node" sends the result back to the exact Link Call that asked. That gives you one shared "format notification" or "lookup device name" routine used from many places, without the overhead of a subflow.
| Need | Use |
|---|---|
| Same logic, different settings per copy | Subflow |
| One shared routine that returns a result | Link Call + Link In + Link Out (return mode) |
| Just tidy wiring between areas or tabs | Link Out → Link In |
3. Catch errors instead of losing them
When a node fails (a JSON parse error, an HTTP request timeout, a Function that throws), it reports an error. Without a Catch node, that error goes to the debug sidebar and log, and the message is dropped. With one, you get the failed message plus msg.error:
| Property | Contains |
|---|---|
msg.error.message | The error text |
msg.error.source.name / .type / .id | Which node failed |
The rest of msg | The message that caused it, so you can retry or log it |
Catch node scope options: all nodes on the tab, selected nodes, or nodes in the same group. Tick Ignore errors handled by other Catch nodes on a tab-wide "catch-all" so a specific handler takes priority.
A practical error branch: catch → function (format) → delay (rate limit: 1 msg/min, drop intermediate) → notification (Telegram, email, or a dashboard notification). The rate limit stops a broken sensor from sending you 500 alerts.
// Format a readable error alert
msg.payload = `Node-RED error in "${msg.error.source.name || msg.error.source.type}": ${msg.error.message}`;
return msg;Make your own Function nodes catchable. Use node.error("Bad reading", msg), passing msg as the second argument. Without the message, the error is logged but Catch nodes never see it. node.warn() doesn't trigger Catch at all.
Watch connections with Status nodes
MQTT, serial and many other nodes report their connection state. A Status node set to watch your mqtt in node outputs msg.status.text such as node-red:common.status.connected or node-red:common.status.disconnected whenever it changes. Wire it to a dashboard text widget or an alert.
Notice devices that go quiet (watchdog)
Errors don't fire when a sensor just stops sending. Use a Trigger node as a watchdog: send nothing, then wait for 5 minutes, then send offline, with Extend delay if new message arrives ticked. Every reading restarts the timer; if readings stop for 5 minutes, you get one offline message. MQTT Last Will on the device is the other half of this: see ESP32 MQTT retained messages and LWT.
4. Validate at the edges, retry with limits
Treat every message from outside Node-RED (MQTT, HTTP, serial) as untrusted, even on your own LAN: check that it exists, has the right shape, and holds finite numbers in a sensible range. A missing reading is not zero, so drop it or flag it rather than letting a gauge or relay act on it.
// Validate an incoming sensor message; report bad ones to Catch nodes
const p = msg.payload;
if (!p || typeof p !== "object" ||
typeof p.temperature_c !== "number" || !Number.isFinite(p.temperature_c) ||
p.temperature_c < -40 || p.temperature_c > 125) {
node.error("Rejected temperature message: " + JSON.stringify(p), msg);
return null;
}
return msg;Bounded retries. For an HTTP call that sometimes fails, catch the error, count attempts on the message, wait, and try again a limited number of times:
// In the error branch: retry up to 3 times, then give up
msg.retries = (msg.retries || 0) + 1;
if (msg.retries > 3) {
node.warn("Giving up after 3 retries: " + msg.error.message);
return [null, msg]; // output 2: alert / log
}
delete msg.error;
return [msg, null]; // output 1: delay node (e.g. 10 s) → back to the http requestUnlimited retry loops can hammer a service that's already down and flood your flow when it recovers.
Keep state across restarts. Context (flow.set(), global.set(), context.set()) lives in memory by default and is lost on restart or deploy. To persist it, add this to settings.js and restart:
contextStorage: {
default: { module: "localfilesystem" }
},Values are then written to disk (flushed every 30 seconds by default). Use it for counters, last-alert times and on/off states, but not for high-rate data, which belongs in a database.
5. Back up, version and test restores
- Export a tab or the whole workspace from Menu → Export (choose JSON, formatted). Credentials are not included, which is good for sharing but means you need
flows_cred.jsonand yourcredentialSecretto restore them. - Version control: enable Projects in settings.js (
editorTheme: { projects: { enabled: true } }) to commit and diff flows with Git from inside the editor. Use a private repository. - Back up the runtime files from
~/.node-red:flows.json,flows_cred.json,settings.js,package.json(the list of palette nodes), and.config.runtime.jsonif you didn't set a credential secret. Full steps and a backup command: Secure Node-RED: HTTPS, MQTT TLS and backups. - Test a restore on a spare machine or a Docker container: copy the files, run
npm installin the user directory, start Node-RED and check the flows deploy and connect. - Before upgrading Node-RED or a palette node, back up first and read the release notes.
Reliability checklist
| Check | Done when |
|---|---|
| Input validation | Every MQTT/HTTP/serial input has a validate step; bad messages go to node.error(..., msg) |
| No silent failures | Each tab has a Catch node wired to a visible, rate-limited alert or log |
| Connection monitoring | Status nodes watch broker and serial connections |
| Watchdogs | A Trigger watchdog (or MQTT Last Will) flags devices that go quiet |
| Bounded retries | Every retry loop has a maximum count and a delay |
| Repeated logic | Shared logic lives in one subflow or Link Call routine |
| Persistent state | Counters and states that must survive a restart use file-backed context |
| Safe commands | Commands are explicit (ON/OFF, not TOGGLE) so repeating one is harmless |
| Backups | Flows, credentials, settings and package list backed up; restore tested |
Troubleshooting
| Problem | Likely cause | Fix |
|---|---|---|
| Catch node never fires | Function uses node.error("text") without msg, or node.warn | Use node.error("text", msg) |
| Catch fires twice for one error | Two Catch nodes with overlapping scope | Tick Ignore errors handled by other Catch nodes on the catch-all |
env.get() returns an empty string | Property not defined on the subflow, or not set on that instance | Add it on the template's Properties tab and set a default |
| Editing one subflow copy changed them all | That's how subflows work | Use subflow properties for per-copy differences |
| Link Call times out | Target section doesn't end in a Link Out in "return" mode | Set the final Link Out to Return to calling link node |
| Context values reset after restart | Default memory context | Configure contextStorage with localfilesystem |
| Alert storm during an outage | No rate limit on the error branch | Add a Delay node in rate-limit mode, dropping intermediate messages |
| Status node shows nothing | It watches different nodes, or the node doesn't report status | Select the node in the Status node's scope; check that node shows a status badge |
FAQ
What is a subflow in Node-RED? A reusable group of nodes that appears as a single node in the palette. Edit the template once and every instance changes; per-instance settings come from subflow properties.
Subflow or Link Call? Use a subflow when each copy needs its own settings or its own state. Use Link Call when you want one shared routine, such as a lookup or formatter, that many flows call and get a result back from.
Can a subflow have a status? Yes. Add a Status node inside the subflow template (newer versions show it as a status output on the template) and send it a status object.
Do Catch nodes catch errors inside subflows? A Catch node inside the subflow handles its errors first. Errors not handled there are passed up to Catch nodes on the tab containing the subflow instance.
Next steps
- Secure Node-RED: login, HTTPS, MQTT TLS and backups: the other half of a production-ready setup.
- Node-RED PIR alerts to Telegram and email: a good flow to turn into a reusable alert subflow.
- Node-RED nodes, flows and msg.payload explained, if the message object is still new.
- Node-RED automation with schedules and context: more on flow and global context.
- MQTT troubleshooting: rc=-2 and rc=5.
Official references: Subflows, Handling errors and Working with context.




