Automate Everything: Setting Up Node-RED with Home Assistant for Powerful Automations

Home Assistant’s built-in automation editor works fine for simple “turn on light at sunset” rules. But when you need conditional logic, complex triggers, or automations that span multiple devices and services, the visual YAML editor becomes a wall.

Node-RED is a flow-based programming tool that connects Home Assistant to anything with an API. Instead of writing nested YAML conditions, you drag and drop nodes to build visual logic flows. Your “if motion detected after sunset and nobody is home and the thermostat says it’s below 65°F” rule becomes a visual pipeline — not a YAML tower.

This guide walks through installing Node-RED in Home Assistant, connecting it to your entities, building your first two automations, and deploying to production.

What You’ll Build

A Node-RED instance running as a Home Assistant add-on, connected to your HA instance via the WebSocket API. You’ll build two production-ready flows:

  1. Motion-activated path lighting — turns on hallway lights when motion is detected, but only between sunset and sunrise, and only if the ambient light level is below a threshold
  2. Weather-based thermostat adjustment — adjusts your thermostat setpoint when rain is forecast within the next hour

What You’ll Need

Item Notes
Home Assistant instance Any platform (RPi, NUC, VM) with add-on support
Home Assistant add-on store Included in HAOS and supervised installations
Existing devices and entities At least one motion sensor, light, and a weather integration

Cost: $0. Node-RED is free and open source. You just need a running Home Assistant instance with add-on capabilities.

Step 1: Install the Node-RED Add-on

Node-RED runs as a Home Assistant add-on, which means installation is one-click:

  1. In Home Assistant, go to Settings → Add-ons → Add-on Store
  2. Search for “Node-RED” — the official add-on is maintained by the Home Assistant community
  3. Click Install (takes about 2–3 minutes on a Raspberry Pi 4/5)

Once installed, don’t start it yet. You need to configure authentication first.

Step 2: Set the Credential Secret

Node-RED uses a credential_secret to encrypt your flow credentials (API keys, tokens, passwords stored inside flows). Open the add-on’s Configuration tab and add:

credential_secret: "replace-with-a-strong-random-string"
system_packages: []
init_commands: []

Generate a strong secret from the terminal of your Home Assistant host:

openssl rand -base64 32 | tr -d /=+ | cut -c1-32

This produces a 32-character alphanumeric string suitable for the credential secret. Without this value set, Node-RED will fail to start [1].

Step 3: Install the Node-RED Companion Integration

Node-RED connects to Home Assistant through a dedicated integration called the Node-RED Companion. Without it, your flows can’t see entities or call services.

  1. In Home Assistant, go to Settings → Devices & Services
  2. Click Add Integration (bottom right)
  3. Search for “Node-RED Companion”
  4. Click through the setup wizard — it auto-discovers the local add-on if installed
  5. No configuration values needed; the integration handles authentication via the add-on’s internal network

Important: If the integration doesn’t find the add-on, ensure the add-on is stopped (not running) during the initial pairing. Start the add-on only after the integration shows “Configured” in Devices & Services [2].

Step 4: Start Node-RED and Open the Editor

  1. Go back to the Node-RED add-on page and click Start
  2. Watch the logs for: [info] Starting flows
  3. Click Open Web UI — this opens the Node-RED flow editor in a new browser tab

You’ll see the Node-RED editor layout:

  • Left sidebar: Node palette with categories (common, function, network, and a “Home Assistant” section with event, entity, service, and trigger nodes)
  • Center: Blank canvas where you build flows
  • Right sidebar: Info tab, debug messages, and help
  • Top bar: Deploy button (red, top right), menu options

The palette’s Home Assistant section should show nodes like Events: state, Call Service, Get Entity, Events: all, and Current State. If any of these are missing, go to Manage Palette → Install and check that node-red-contrib-home-assistant-websocket version 0.70.0 or later is installed.

Step 5: Build Flow 1 — Motion-Activated Path Lighting

This flow turns on hallway lights when motion is detected, but only between sunset and sunrise, and only if the ambient light level is below 20 lux.

Add the Trigger

  1. Drag an Events: state node (from the Home Assistant section) onto the canvas
  2. Double-click to configure:
    • Entity ID: binary_sensor.hallway_motion (replace with your motion sensor’s entity ID)
    • State: on — fires only when motion is detected (state changes to “on”)
    • Name: “Motion Detected”
  3. Click Done

The node turns green when configured. Red means the entity ID isn’t found — check the spelling against your Home Assistant entity list (Developer Tools → States).

Add the Time Condition

Node-RED doesn’t have a built-in “between sunset and sunrise” node, so you write a small JavaScript function that checks the sun entity:

  1. Drag a Function node onto the canvas
  2. Double-click and paste:
    const sun = global.get("homeassistant").homeAssistant.states["sun.sun"];
    const now = new Date();
    const sunset = new Date(sun.attributes.next_setting);
    const sunrise = new Date(sun.attributes.next_rising);
    
    // Return the message only if it's dark (after sunset or before sunrise)
    if (now > sunset || now < sunrise) {
        return msg;
    }
    // Otherwise, stop the flow by returning null
    return null;
  3. Name it “Dark outside?”
  4. Click Done

Add the Lux Check

  1. Drag an API current state node onto the canvas (Home Assistant section)
  2. Configure:
    • Entity ID: sensor.hallway_lux (or your light sensor entity)
    • Name: “Check Lux”
  3. Drag a Switch node (Functions section) after the API node
  4. Configure the Switch:
    • Property: msg.payload.state
    • Test: Select < from the dropdown and enter 20
    • Name: “Dark enough?”
  5. Click Done

Add the Light Action

  1. Drag a Call Service node onto the canvas
  2. Configure:
    • Domain: light
    • Service: turn_on
    • Entity ID: light.hallway_lights (replace with your light)
    • Data: {"brightness_pct": 30, "transition": 2}
    • Name: “Turn on lights dim”
  3. Click Done

Add the Auto-Off After Delay

  1. Drag a Delay node after the Switch output
  2. Configure:
    • Delay type: fixed
    • Delay: 5 minutes
    • Name: “Wait 5 min”
  3. Drag another Call Service node after the Delay
    • Domain: light
    • Service: turn_off
    • Entity ID: light.hallway_lights
    • Name: “Turn off lights”

Wire and Deploy

Connect the nodes in sequence: Events: stateFunction (Dark outside?)API current state (Check Lux)Switch (Dark enough?)

From the Switch output, wire two branches:

  • Output 1 (match):Call Service (Turn on lights dim)Delay (Wait 5 min)Call Service (Turn off lights)
  • Output 2 (no match): Leave unconnected (flow stops)

Click the red Deploy button. Test by triggering your motion sensor — the lights should come on dimly only when it’s dark and the room is below 20 lux, then turn off after 5 minutes.

Step 6: Build Flow 2 — Weather-Based Thermostat Adjustment

This automation monitors the weather forecast and adjusts your thermostat when rain is expected. It saves energy by pre-heating or pre-cooling before a weather change, reducing HVAC runtime during the storm.

  1. Drag an Events: state node onto the canvas

  2. Set Entity ID to your weather entity (e.g., weather.home — the default from the Met.no integration)

  3. Set State: to "" (empty — fires on any change)

  4. Drag a Function node and connect it:

    const forecast = msg.payload;
    const nextHour = forecast?.attributes?.forecast?.[0];
    
    if (!nextHour) return null;
    
    const rainyConditions = ["rainy", "pouring", "thunderstorm", "lightning", "drizzle"];
    if (rainyConditions.includes(nextHour.condition)) {
        msg.forecastTemp = nextHour.temperature;
        return msg;
    }
    return null;
  5. Name it “Rain check?”

  6. Drag a Call Service node and connect it:

    • Domain: climate
    • Service: set_temperature
    • Entity ID: climate.thermostat (replace with your thermostat)
    • Data: {"temperature": 68, "hvac_mode": "heat"} (adjust to your preferred temperature)
    • Name: “Set heat to 68°F”
  7. Click Deploy

Now, when the Met.no forecast changes and rain is expected within the next hour, your thermostat adjusts to 68°F automatically. You can expand this to cooling mode in summer by checking for “sunny” or “hot” conditions and calling climate.set_temperature with hvac_mode: cool.

Configuration Details

Using Secrets in Node-RED

Hard-coding entity IDs works for single-instance setups, but if you want to share flows or keep configuration separate, use Node-RED’s environment variables:

  1. Go to the Node-RED add-on Configuration tab
  2. Add under env_vars:
    env_vars:
      - name: MOTION_SENSOR
        value: binary_sensor.hallway_motion
      - name: HALLWAY_LIGHT
        value: light.hallway_lights
  3. In your flow, reference them as env.get("MOTION_SENSOR") in Function nodes or use the env variable in node configuration fields that support it

Debugging Flows

Every Node-RED installation includes a debug node (bug icon in the palette). Drag one onto the canvas and wire it to any node output. When you deploy, debug messages appear in the right sidebar’s debug tab showing the full message object — payload, topic, and metadata.

Pro tip: Add a debug node to the output of every Function node during development. You’ll see exactly what data passes through, which turns a broken flow into a fixable one in seconds.

Troubleshooting

Symptom Likely Cause Fix
“Entity not found” errors Node-RED hasn’t synced entities yet Restart the Node-RED add-on after the Companion Integration finishes setup
Flows show “Disconnected” banner Companion Integration lost its connection Go to Devices & Services → Node-RED Companion → Reconfigure
global.get("homeassistant") returns undefined Outdated node-red-contrib package Manage Palette → Upgrade node-red-contrib-home-assistant-websocket to ≥ 0.70.0
Add-on won’t start Port 1880 already in use Check add-on config for port setting; change to 1881 if conflicted
Flow runs once then never again Node wired to wrong output port Verify switch/function node wiring — expand the node to see all output ports
“TypeError: Cannot read properties of undefined” Entity state is unavailable or entity doesn’t exist Check entity ID in Developer Tools → States; add a “Current State” node before the Function
Delayed responses from Call Service HA is processing other automations first Check if your YAML-based automations conflict; consider disabling the equivalent YAML automation
Deploy button stays grey Flow contains syntax errors in a Function node Open each Function node and check for red underlines in the code editor

What You’ve Built

You now have a visual automation engine running alongside Home Assistant. Node-RED handles complex logic — conditional flows, data transformations, and multi-step sequences — while Home Assistant continues managing device states and integrations.

Compared to YAML automations, Node-RED gives you:

  • Debug visibility: Each deployed node shows execution status at a glance — green dot (executed), red dot (error), grey dot (never triggered)
  • Error handling: Add a catch node to the canvas and it intercepts errors from any connected node, allowing you to build fallback logic
  • Reusable subflows: Select a group of nodes, right-click, and create a subflow. Export it as JSON and import into another instance — or share it with the community
  • Data transformation: JavaScript Function nodes let you reshape payloads, combine sensor readings, and compute derived values without writing Home Assistant templates

The total cost is zero. Node-RED runs entirely locally — no subscriptions, no cloud accounts, no additional hardware.

Going Further

  • Dashboard UI: Install node-red-dashboard from Manage Palette to build visual dashboards with gauges, charts, and sliders that run separately from Home Assistant’s frontend
  • MQTT: Add an MQTT broker and use the MQTT nodes in Node-RED to subscribe directly to topics from ESPHome sensors, bypassing Home Assistant entirely for latency-critical automations
  • Email and notifications: Use the e-mail node (requires SMTP credentials) or the Home Assistant Call Service node with notify.mobile_app to send alerts when critical sensors trigger
  • Schedule nodes: The node-red-contrib-suncalc palette gives you sunrise/sunset event nodes without writing JavaScript, plus moon phase and golden hour events
  • Flow library: Browse thousands of community-contributed flows at flows.nodered.org — search for “home assistant” to find weather alerts, holiday light shows, and presence simulation flows you can import directly [4]

Sources: [1] Node-RED Home Assistant add-on documentation — github.com/hassio-addons/addon-node-red [2] Node-RED Companion Integration — github.com/zachowj/hass-node-red [3] node-red-contrib-home-assistant-websocket — github.com/zachowj/node-red-contrib-home-assistant-websocket [4] Node-RED Flow Library — flows.nodered.org [5] Home Assistant Automation Documentation — home-assistant.io/docs/automation

← Back to guides