Troubleshooting
Why a Node-RED function node throws require is not defined
Short answer
The ReferenceError comes from the Function node's sandbox, which never exposes require, so the flow opens no connection at all. Route the SQL through the MySQL palette node, watch availability with one dedicated health check, and let a Catch node scoped to that node latch a single alarm that clears only on a valid reply. Worst-case detection time is the check interval plus the connection timeout.

On this page
- Why does a Node-RED Function node throw require is not defined?
- Does installing the module with npm fix the error?
- How should a Node-RED flow connect to MariaDB instead?
- How do you detect a database outage from Node-RED?
- How do you scope a Catch node to only the health-check node?
- How fast does the outage alarm actually fire?
- Why do all my database nodes raise the same outage error?
- How do you verify the failure path before you trust it?
- Questions asked
A ReferenceError: require is not defined inside a Node-RED Function node means the runtime stopped at that line and never reached the database code behind it: no pool, no TCP connection, no login, no query. Function nodes execute in a restricted JavaScript context that does not expose require, so a database script written for a plain Node.js program cannot run in one, on any hardware the flow happens to live on. The fix is architectural, not an install: put the SQL in a MySQL database node from the palette, watch availability with one dedicated health-check path, and scope a Catch node to that path so an outage raises exactly one latched alarm. This article gives you the reason, the replacement flow, the alarm logic, and the detection-latency math that decides your check interval.
Why does a Node-RED Function node throw require is not defined? #
Because Function nodes run in a restricted JavaScript context that does not expose the require function, the runtime raises ReferenceError at the line that calls it and stops before opening any TCP session, logging in, or sending a single query to the database.
Node-RED does not execute Function node code as a standalone program file. It wraps the code in a sandbox and injects the objects the platform documents for that context: msg, node, the context stores context, flow and global, and the helpers for sending messages on. require is deliberately absent from that scope, so the identifier cannot resolve and JavaScript raises the error before anything else in the function runs.
The line and column in the error you saw, for example line 2 where a pasted pool example calls require('mariadb'), locate the first forbidden call, and nothing after it executed. That is why the database server's own log shows no connection attempt from this code: authentication never happened, so there is nothing to find on the server side. Treat the exact position as a symptom that moves with your code; the sandbox rule behind it is documented Node-RED behavior and is identical on a development laptop, a compact edge gateway or a container image.
Does installing the module with npm fix the error? #
No, because a package installed at the operating-system level stays invisible to Function node code while the runtime's external-modules option is disabled, which is its default, so the identical ReferenceError returns on the next deploy.
There is a documented route for this, and it is closed by default. Node-RED 1.3 introduced the functionExternalModules option in the runtime's settings file (settings.js): once an administrator enables it and restarts Node-RED, each Function node gains a Setup tab where the modules that node may load are declared. The declared package still has to be installed in the runtime's own node directory, so this route only exists where you control the runtime enough to install packages at all.
Even where the console is available, treat Function-node require as the exception on a plant-floor runtime. Every declared module has to be reinstalled and re-declared across runtime upgrades, an appliance image without a console gives you no way to run the install, and a hand-installed driver duplicates what a palette node already does. For SQL work the palette node needs none of it, and the rest of this article uses that path.
How should a Node-RED flow connect to MariaDB instead? #
Use a database node from the palette manager, such as node-red-node-mysql: the node owns the connection, keeps the credentials in its own protected fields, and executes the SQL you pass in msg.topic, so no require call appears anywhere in the flow.
Install it from the palette manager in the editor and deploy. The node's configuration screen holds the host, port, database and credentials, so the password lives in the node's protected credential store instead of flow source text. For a remote server, for example a MariaDB host at 192.168.1.50, the Node-RED runtime needs nothing more than network reachability to that listener, because it is a client and the database stays where it is.
Queries ride the normal message path: the SQL statement goes in msg.topic and the values for a parameterized insert go in msg.payload, with statement-building done in a Change or Function node, which is string handling, not module loading. Generate success only from the database node's own success output; a script that returns a connected message right after starting an asynchronous connect is reporting a promise that has not settled. For the message shape of a parameterized insert end to end, this site's walkthrough covers it: Saving Node-RED OPC UA values to MySQL through a template insert. Multiple database nodes can reference one shared connection configuration, which matters once several nodes target the same server.
How do you detect a database outage from Node-RED? #
Build one dedicated health-check path: an Inject node fires it on a fixed interval, a Change node puts a read-only query such as SELECT @@VERSION in msg.topic, and a Catch node scoped to that database node turns the failed check into the outage alarm.
The order of operations inside the database node decides what a failing check can show. On every check the client first opens or reuses a TCP connection and completes the login; only then does the server parse and execute the statement in msg.topic. When the server or the network is down, the statement never runs, so the version query cannot gracefully report unavailability. The connection error the node raises is itself the health signal, and it arrives whatever the query text was.
Use the query for what it does well: proving a healthy path end to end through the same listener, credentials and parser as production traffic. Wire the success output to record the last valid reply and clear the alarm; let the scoped Catch treat any error from that node, whether a refused connection, a login failure or a timeout, as an unhealthy check. Where a refused connection comes from and how to separate it from credential or port problems, this site's walkthrough covers in detail: Fixing ECONNREFUSED when Node-RED connects to a remote SQL database.
How do you scope a Catch node to only the health-check node? #
Open the Catch node's scope setting and select only the health-check database node; an unscoped Catch collects errors from every eligible node on the tab, including errors that rise out of subflows, so a runtime with many database nodes reports one outage once per node.
Name the health-check database node distinctly first, then tick exactly that node in the scope list. The list shows node names, and default-named nodes are hard to tell apart once a tab holds several of them.
Every error a Catch delivers carries msg.error.source.id and msg.error.source.name, so the handling Function node can confirm the error came from the health path before it touches the alarm state. That filter matters because during a real outage the flow's other database nodes raise their own errors at the same time; those belong to their own write-error handling, not to the availability alarm.
How fast does the outage alarm actually fire? #
Worst-case detection latency is one health-check interval plus the connection timeout: with a 10 s inject interval and a 5 s connection timeout the alarm lands about 15 s after the server stops answering, and best case is the timeout alone.
Worked example, with illustrative values you replace from your own tolerance: a 10 s Inject interval and a 5 s connection timeout. The server stops answering 1 s after a check completed. The flow waits the remaining 9 s of the interval, the next check starts and spends its full 5 s failing to connect, so the scoped Catch fires at 9 + 5 = 14 s after the failure. Worst case, the server dies immediately after a completed check and the same sum reads 10 + 5 = 15 s; best case, the failure lands just before a scheduled check and detection is the 5 s timeout alone.
Decision: size the interval at or below half the detection budget you can defend to whoever owns the downtime consequences, and set the timeout no larger than the extra lag you accept beyond the interval. A 30 s budget decomposes as the 10 s interval plus the 5 s timeout, leaving 15 s of margin. These numbers are example inputs, not node defaults. The effective timeout is whatever your installed database node and its driver apply, and where the node exposes no timeout field you measure the real failure-to-alarm time during the verification window below and size the interval from that measurement.
Why do all my database nodes raise the same outage error? #
Give every database node that targets one server the same shared connection configuration, run the health check on a single dedicated path, and make the alarm edge-triggered: set it on the first failure, keep it latched through repeats, clear it only when that path returns a valid row.
Each database node holds its own connection, so one dead server fails every node independently: with 17 database nodes pointed at one MariaDB host, one outage produces 17 failure messages per firing interval. That flood is a count of connections, not a measure of severity. Reduce it where the flow allows: nodes that share one connection configuration fail as one, and Link nodes can route several logic branches through fewer database execution paths. Keep a separate connection only where transaction isolation or a distinct credential set genuinely requires it.
Then make the alarm edge-triggered so the remaining error traffic cannot bury it. Compare each new health state against a stored state in flow context, for example the key database_alarm: set it and send one failure notification on the first unhealthy check, change nothing while failures repeat, clear it and send one recovery notification on the first valid reply. A level-triggered design that notifies on every failed check sends one message each interval, which is 6 a minute at the example interval and 360 in an hour of downtime. That is how an alarm gets ignored on the day it matters.
How do you verify the failure path before you trust it? #
Prove both transitions in one maintenance window: confirm the healthy branch clears the alarm, take the database down through an approved server-side procedure, check that the scoped Catch fires exactly one failure notification, then restore the service and confirm one recovery on the next successful check.
Run this sequence and keep the measurements:
- Healthy baseline: inject one manual check, confirm a result row reaches the success branch, and confirm the alarm key in flow context is clear.
- Failover: take the database down with the approved server-side procedure and record the wall-clock time. Never stop a plant service from an exec node inside the production flow; a flow that can issue service-stop commands is an OT-security finding in its own right.
- Failure side: confirm the scoped Catch reports the health-check node in the error source, the alarm sets, and exactly one failure notification leaves the flow.
- Latency: measure from the recorded stop time to the notification and compare it with the interval-plus-timeout prediction.
- Recovery: restore the service, confirm the next scheduled check returns a row, the alarm clears and exactly one recovery notification goes out.
- Side effects: inspect the production write paths that errored during the window and decide their behavior deliberately, either fail fast into an alert or queue and replay with store-and-forward SQL buffering during MES outages.
If both notifications arrive exactly once and the measured latency sits inside the budget, the health path is trustworthy. If the Catch fires more than once per outage, or never fires at all, fix the scope before production depends on this path.
Questions asked
Does a Catch node also catch errors my own Function nodes throw?
Yes. A Catch node receives errors from Function nodes as well as database nodes, limited to the scope you select. A deliberate throw used for input validation arrives the same way as a connection failure, so either keep validation throws outside the health-check path's scope or filter by the error source before the alarm logic runs.
What happens if the database node exposes no timeout setting?
Then the TCP connect timeout governs, and it can stretch far beyond your alarm budget. Measure the real failure-to-alarm time during the verification window and size the check interval from that measurement. If the wait is unacceptable, add a watchdog that raises the alarm when no completed check result arrives within the interval plus a maximum wait you set.
Should the health check query a production table instead of a status query?
No. Use a read-only query that returns one fixed value: it needs no table permissions, adds negligible load, and still exercises the connection, the login and the query parser on the same server and credentials the production writes use. A query against a busy production table measures table contention along with availability, which muddies the signal.
Where should the MariaDB credentials live?
In the database node's configuration fields. Node-RED keeps node credentials in a separate protected store, not in the flow JSON you export or copy, so the password does not travel with backups of the flow. A pasted script that declares the connection in code puts the password in plain text in the editor, in exports and in every copy of both.
Can one health check cover two different database servers?
Run one health-check path per server, each with its own scoped Catch and its own alarm. A single check cannot report which server failed, and a server whose check succeeds can mask the other one's failure. The transition logic stays the same on each path: latch on the first failure, clear only on that path's own valid reply.

