Skip to content

Tutorial

Your First Node-RED Flow: Inject, Function and Debug

Build your first working Node-RED flow with Inject, Function and Debug nodes. Learn how messages and msg.payload move through a flow, deploy changes, inspect output, import a ready-made flow and fix the most common beginner mistakes.

Your First Node-RED Flow: Inject, Function and Debug

What You Will Build

This tutorial builds a tiny flow that produces a visible result, changes a message and shows the output in Node-RED's Debug sidebar. No Raspberry Pi GPIO, sensor or MQTT broker is needed. The goal is to learn how messages move through the editor before you attach real hardware, because every later Node-RED project (MQTT dashboards, sensor logging, ESP32 APIs) uses exactly the same mechanics.

By the end you will:

  • Understand what a node, a wire, a message and msg.payload actually are
  • Build and deploy a three-node flow: Inject → Function → Debug
  • Read the Debug sidebar and know what its output means
  • Transform text, numbers and objects safely in a Function node
  • Import a finished flow from JSON and export your own
  • Fix the beginner mistakes that cause "nothing happens"

Time: about 30 minutes. Skill level: beginner. You only need a running Node-RED editor.

Flow-Based Programming in Five Sentences

Node-RED is a visual tool for wiring together devices, services and logic. You drag nodes onto a canvas. Each node does one job: produce data, transform it, send it somewhere or show it. You connect nodes with wires, and the runtime passes messages along those wires. A message is a JavaScript object, and its main property by convention is msg.payload. A wire is a route for messages, not an electrical connection, so you can wire a node to nodes that have nothing to do with hardware.

A Quick Tour of the Editor

Open Node-RED in a browser. On the same computer it is normally http://localhost:1880. On a Raspberry Pi or another machine, use that machine's address and the editor port, which defaults to 1880. If you still need to install it, follow Install Node-RED on Raspberry Pi 5 first. The browser is only the editor. The runtime that executes your flows is a separate program on the server.

The editor has four areas:

  • Palette (left): the list of available nodes, grouped by category.
  • Workspace (centre): the canvas with tabs for each flow.
  • Sidebar (right): tabs for Help, Debug, Configuration nodes and Context data. You will use Debug constantly.
  • Header (top): the red Deploy button and the menu.

The message object

Every message has at least an automatically generated _msgid. Most nodes add payload and often topic. The payload can be a string, number, Boolean, array or object. Because it can be anything, inspect the real message instead of guessing its type. This is the single most useful habit in Node-RED.

1. Create the Flow

Click the + at the end of the tab bar to create a new flow tab and double-click the tab to name it "First flow". Then drag three nodes from the palette onto the canvas: inject (Common), function (Function) and debug (Common).

To wire them, hover over the small grey port on the right side of Inject until it highlights, then drag to the port on the left side of Function. Do the same from Function to Debug. A wire always goes from an output port (right) to an input port (left).

2. Configure Inject

Double-click the Inject node. By default it sends a timestamp. Change the payload type to string and type hello as its value. Name the node "Send hello" so it is easy to recognise, and click Done.

Inject can fire once on start, repeat on a schedule, or run when you click the small button on its left edge. For now, use the button. That makes each test deliberate and repeatable.

3. Configure the Function Node

Double-click Function, name it "Add SolderHub prefix", and replace the code on the On Message tab with this:

sketch.ino
msg.payload = "SolderHub says: " + String(msg.payload) + "!";
return msg;

The node receives the message as msg. The first line replaces the payload with a new string. String() converts whatever arrived into text first, so the code does not break if the payload was a number. The second line returns the message object to send it onward.

Returning msg matters. If you return a plain string instead, Node-RED reports an error such as "function tried to send a message of type string", because the next node expects a message object, not a value. Returning the same object also keeps every other property that earlier nodes added, such as topic and _msgid.

The Function node has three tabs: On Start (runs once when the flow starts), On Message (runs for every incoming message) and On Stop. For now you only use On Message.

4. Configure Debug, Deploy and Run

Double-click the Debug node and make sure its output is set to msg.payload. Name it "Show result". Click Done.

Now click the red Deploy button. Until you deploy, the runtime keeps running the previous version of your flow. A small blue dot on a node means it has changes that are not yet deployed. This is the number one reason beginners think a flow is broken.

Open the Debug sidebar (the bug icon), then click the button on the Inject node once. You should see:

Output
SolderHub says: hello!

Each Debug entry shows a timestamp, the name of the Debug node that produced it, the property shown (msg.payload), the data type and length (here string[22]) and the value. The diagram below follows the message through the flow. The Function node changes only the payload, and the _msgid stays the same.

The same message at each stage: Inject creates payload “hello”, Function replaces it, Debug displays it

Make the Flow Run by Itself, and Remember Things

Scheduling the Inject node

So far you clicked a button for every test. The Inject node can also run on its own. In its settings, Repeat can send a message every few seconds, minutes or hours, or at specific times on selected days. The option Inject once after a short delay sends one message whenever the flow starts, which is useful for setting an initial state. A repeating Inject is also an easy way to simulate a sensor while you build the rest of a flow. Use a slow interval at first, so the Debug sidebar stays readable.

Keeping a value between messages

A Function node forgets its local variables after every message, because the code runs again from the top each time. To remember something, such as a running count or the last reading, use context. Context has three scopes: context (this node only), flow (every node on the same tab) and global (everywhere). This counter shows the idea:

script.js
let count = context.get("count") || 0;
count += 1;
context.set("count", count);

msg.payload = "Message number " + count;
return msg;

Set Inject to repeat every few seconds and watch the number climb in the Debug sidebar. Two cautions apply. By default, context lives in memory, so the counter restarts from zero whenever Node-RED restarts, and keeping values across restarts requires enabling persistent context storage in the Node-RED settings file. And because flow and global values are shared, give them clear names so two parts of a project do not overwrite each other by accident.

A good rule is to keep state in context only when you truly need history, such as a previous reading for a change detector or a counter. When you only need to pass information forward, add it to the message itself, where it is visible in Debug and travels with the data.

Use the Flow Without Building It: Import

Node-RED flows are stored as JSON, so you can share them as text. To try the finished flow, open the menu (top right), choose Import, paste the JSON below, click Import and then Deploy.

config.json
[
  {"id":"f1a2b3c4d5e60001","type":"tab","label":"First flow","disabled":false,"info":""},
  {"id":"a1b2c3d4e5f60001","type":"inject","z":"f1a2b3c4d5e60001","name":"Send hello",
    "props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,
    "topic":"","payload":"hello","payloadType":"str","x":150,"y":100,
    "wires":[["a1b2c3d4e5f60002"]]},
  {"id":"a1b2c3d4e5f60002","type":"function","z":"f1a2b3c4d5e60001",
    "name":"Add SolderHub prefix",
    "func":"msg.payload = \"SolderHub says: \" + String(msg.payload) + \"!\";\nreturn msg;",
    "outputs":1,"timeout":0,"noerr":0,"initialize":"","finalize":"","libs":[],
    "x":380,"y":100,"wires":[["a1b2c3d4e5f60003"]]},
  {"id":"a1b2c3d4e5f60003","type":"debug","z":"f1a2b3c4d5e60001","name":"Show result",
    "active":true,"tosidebar":true,"console":false,"tostatus":false,
    "complete":"payload","targetType":"msg","statusVal":"","statusType":"auto",
    "x":610,"y":100,"wires":[]}
]

To share your own flows, select the nodes, open the menu and choose Export. Treat exported flows like code: they can contain credentials and addresses, so review them before posting publicly.

5. Experiment Safely

The best way to learn is to change one thing and observe the result.

Change the input

Edit Inject, set the payload to Raspberry Pi 5, then Deploy and click it again. The output becomes SolderHub says: Raspberry Pi 5!. You changed the data without touching the logic.

Do arithmetic on a number

Set Inject's payload type to number with the value 21.5. Replace the Function code with a Celsius to Fahrenheit conversion:

script.js
msg.payload = msg.payload * 9 / 5 + 32;
return msg;

Deploy and inject: the Debug sidebar shows 70.7, and its type has changed to number.

Validate before you calculate

Real data is messy. Sensors and APIs send strings such as "24.5", empty values and nonsense. In JavaScript, Number("") is 0, which would turn an empty reading into a perfectly valid-looking zero. Guard against it:

script.js
const raw = msg.payload;
const n = Number(raw);

if (raw === "" || raw === null || Number.isNaN(n)) {
  node.warn("Ignoring invalid reading: " + raw);
  return null;          // returning null stops the message here
}

msg.payload = n * 9 / 5 + 32;
node.status({fill: "green", shape: "dot", text: n + " °C"});
return msg;

Three useful tools appear here. node.warn() writes a message to the Debug sidebar so that mistakes are visible. return null deliberately drops a message instead of passing bad data downstream. node.status() shows a short status under the node on the canvas, which is a quick way to see what a node is doing without opening the sidebar.

Work with an object

Set Inject's payload type to JSON with the value {"room":"kitchen","temp":24.5}. Use this Function code:

script.js
const d = msg.payload;
if (typeof d !== "object" || d === null || typeof d.temp !== "number") {
  node.warn("Unexpected payload shape");
  return null;
}
msg.payload = d.room + ": " + d.temp + " °C";
return msg;

The output is kitchen: 24.5 °C. Notice that you accessed fields with dot notation and checked the shape first. This is the pattern you will use for every MQTT or HTTP message that arrives as JSON.

See the whole message

In the Debug node, change the output from msg.payload to complete msg object. You will now see _msgid, payload and topic. Showing everything is ideal while learning. Showing only the payload keeps output tidy once you know what is in the message. When a flow is busy, use the filter at the top of the Debug sidebar to show only the current flow, and the bin icon to clear it.

Beginner Mistakes and How to Fix Them

The flowchart gives a quick order of checks when the Debug sidebar stays empty.

Troubleshooting flowchart: check deployment, wires, Debug enabled and return msg in the Function node, then read the log
SymptomLikely causeFix
Nothing appears in DebugNot deployed, or Debug sidebar closed or node disabledClick Deploy, open the Debug sidebar, and make sure the Debug node's button is green.
A blue dot shows on a nodeChanges not deployedClick Deploy.
Function error about message typeFunction returned a string instead of msgEnd the code with return msg;.
Output disappears after the Function nodeThe code returns null or has no returnCheck every path returns msg unless you intend to stop.
NaN appearsText converted to a number without validationCheck with Number.isNaN() before using the result.
Value is 0 when the input was emptyNumber("") equals 0Test for an empty string first.
Debug floods with messagesA fast Inject or sensor streamDisable or delete noisy Debug nodes after testing.
Editor loads but nothing runsWrong server or the runtime is stoppedConfirm the address and port, and check the Node-RED service or log.

Good Habits From Day One

  • Name every node. "Add SolderHub prefix" beats "function 1" when a flow has thirty nodes.
  • Keep Function nodes short. If one grows past a screen, split it into smaller nodes that each do one job.
  • Validate input before using it, especially from networks and sensors.
  • Use Debug generously while building and remove or disable it when the flow is stable.
  • Export a backup of your flows before major changes.

Frequently Asked Questions

Do I need to know JavaScript? Not much to begin. Function nodes use JavaScript, but you can build many flows from the standard nodes with no code, and the snippets above cover the basics.

What is the difference between Deploy modes? The Deploy button has a dropdown. Full restarts everything, Modified Flows restarts only changed flow tabs, and Modified Nodes restarts only changed nodes. The default is fine for learning.

Where does msg.payload come from? It is only a convention. Most core nodes read and write it, which makes nodes easy to combine.

Can one Inject node feed several nodes? Yes. Draw several wires from the same output port, and each receives a copy of the message.

Is the Function node the best way to do everything? No. For simple changes, nodes such as Change, Switch and Template are clearer and easier to maintain. Use Function when you need real logic.

Summary

You built Inject → Function → Debug, deployed it, and followed one message from creation to display. You learned that wires carry messages, that msg.payload is a convention and not a rule, that returning msg is mandatory, and that validation belongs in every Function that handles outside data. With those habits, the same flow shape scales from "hello" to sensor dashboards and cloud integrations.

What to learn next

Official references: Working with messages and Writing Functions.

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.