NodeRED

Node-RED Global Variables: Two Methods That Actually Work

Node-RED makes visual programming accessible. But once your flows grow, you will inevitably need to share data across different parts of your automation. That is where global variables become essential. A new tutorial from creatifwerks.com walks through exactly how to handle this.

Global variables let you store values accessible from any flow in your Node-RED instance. Without them, passing data between separate flows requires workarounds that quickly become messy. The tutorial covers two distinct approaches, each suited for different comfort levels.

At a Glance

  • Two methods exist for declaring global variables in Node-RED
  • Method one uses the Change node, no code required
  • Method two uses the Function node with simple JavaScript
  • Global variables work across all flows in your instance
  • Both methods tested and verified in the tutorial

Method One: The Change Node Approach

The Change node offers the simplest route. You do not need to write any code. The interface handles everything.

Start by creating two flows in your Node-RED environment. Name them anything you like. The tutorial uses "Flow 1" and "Flow 2" for clarity. These separate spaces let you test how data transfers between isolated areas.

In Flow 1, drag out an Inject node. Configure it to pass a string value to msg.payload. The tutorial uses "This is A Global String 1" as an example. When triggered, this node injects that text into the message stream.

Next, add a Change node to Flow 1. This is where the magic happens. The node configuration maps msg.payload to a new global variable called firstGlobalString. The interface makes this straightforward: you set a rule that reads from msg.payload and writes to global.firstGlobalString.

Connect the Inject node to the Change node. You now have a complete chain. Triggering the Inject node passes the string through the Change node, which stores it as a global variable.

To verify this works, head to Flow 2. Add an Inject node configured to read from global.firstGlobalString. Add a Debug node to display the output. When you trigger this second Inject node, it retrieves the value stored in Flow 1 and displays it in your debug panel.

This method works well for straightforward data passing. You never touch code, and the visual interface makes the logic clear at a glance.

Method Two: The Function Node Approach

The Function node gives you more power. You write JavaScript that directly manipulates the global context.

Set up Flow 1 the same way as before: an Inject node feeding a string value into msg.payload. The example string changes to "This is A Global String 2" to distinguish it from method one.

This time, add a Function node instead of a Change node. The configuration uses global.set() to write the variable. The tutorial code looks like this:

“`javascript

Global.set('secondGlobalString', msg.payload)

Return msg;

“`

This two-line function takes msg.payload and stores it under the key 'secondGlobalString' in the global context. The return msg statement passes the message onward through the flow.

Retrieving this variable in Flow 2 mirrors method one. An Inject node reads from global.secondGlobalString, and a Debug node displays the result. The tutorial confirms both approaches produce the expected output.

Function nodes suit more complex scenarios. You can perform calculations, combine multiple values, or add conditional logic before storing data globally.

Our Analysis

The Change node approach appeals to users who prefer visual tools. It removes friction for beginners or anyone uncomfortable writing code. The tradeoff is flexibility: you cannot easily transform data before storing it.

Function nodes unlock full JavaScript capabilities. You can transform payloads, handle errors, or implement business logic before committing values to global context. The learning curve is steeper, but the payoff is worth it for non-trivial automations.

Most Node-RED users find themselves reaching for both methods over time. Simple state sharing uses Change nodes. Complex data transformation uses Function nodes.

A Worked Example

Say you build a temperature monitoring system. Flow 1 collects readings from a sensor every minute. You want to track the daily high temperature across multiple flows.

Using a Change node, you could simply store each new reading. But what if you only want to update when the new reading exceeds the stored maximum?

A Function node handles this cleanly. Your code reads the current global maximum, compares it with the new reading, and only updates if the new value is higher. The Change node cannot perform this conditional logic without additional configuration complexity.

What This Means for You

Global variables transform Node-RED from isolated flow snippets into cohesive automation systems. Whether you use Change nodes, Function nodes, or both depends on your needs.

Start with the Change node method if you are new to Node-RED. It teaches the concept without overwhelming you with syntax. Graduate to Function nodes when you need logic beyond simple storage.

Key takeaways

  • Global variables enable data sharing across all Node-RED flows
  • Change nodes provide code-free global variable creation
  • Function nodes offer full JavaScript power for complex logic
  • Both methods tested and verified working
  • Choose your method based on transformation needs, not just storage

Frequently asked questions

Can global variables in Node-RED persist after a restart?

By default, global context is memory-only. For persistence, you need to configure context storage to use a file or database backend.

Are there any naming restrictions for global variables?

Variable names follow JavaScript identifier rules. They cannot start with numbers or contain spaces. CamelCase or highlights work well.

Can one flow overwrite a global variable created by another flow?

Yes. Global variables have no built-in access control. Any flow can read or modify any global variable.

How many global variables can Node-RED handle?

There is no practical limit within reasonable memory constraints. Performance may degrade with thousands of variables in low-memory environments like Raspberry Pi.

Do I need to declare global variables before using them?

No. Node-RED creates variables automatically when you first set them using global.set() or through Change node configuration.

Source: creatifwerks.com

Related