FlowKit

Connect MQTT to n8n: drive sensors and home automation from your workflows

Published 26 August 2026 · 8 min read

A fifteen-euro sensor publishes a reading every thirty seconds to a Mosquitto broker. Home Assistant displays it, Zigbee2MQTT relays it, Tasmota and ESPHome speak the same language. But the moment you need to cross that reading with tomorrow's forecast, wake up an on-call engineer or have an LLM analyse a drift, home automation hits its ceiling: it can display and trigger, not reason. n8n fills that gap with two nodes and one credential. This guide covers their real parameters, the protocol mechanisms that surprise newcomers — QoS, retain, Last Will — and the one thing people discover too late: a trigger's persistent connection.

MQTT in three minutes

A central broker — Mosquitto, EMQX, HiveMQ, or the one bundled with Home Assistant — receives every message. Producers publish to a topic, a slash-separated hierarchical string (home/lounge/temperature, plant/line2/motor/vibration); consumers subscribe and receive whatever flows through it, without ever knowing the producers. Two wildcards make subscriptions flexible: + replaces a single level (home/+/temperature catches the lounge and the kitchen, but not home/lounge/sensor1/temperature), # replaces every following level and may only appear at the end of a pattern.

The fundamental difference with an HTTP webhook is the direction of the connection: the client opens it towards the broker and keeps it open. No port forwarding, no public IP on the sensor side — which is why the protocol suits a self-hosted n8n instance on a Raspberry Pi so well. That choice has a measurable cost: Víctor Seoane, Carlos Garcia-Rubio, Florina Almenares and Celeste Campo compare MQTT and CoAP on constrained devices in "Performance evaluation of CoAP and MQTT with security support for IoT environments", published in 2021 in Computer Networks (vol. 197, art. 108338 — see on Google Scholar). They measure bandwidth and CPU load — both of which translate into power draw — and show that securing the transport, like raising the reliability level, weighs on the energy budget of a battery-powered sensor.

QoS, retain and Last Will

QoS 0 (at most once): the message leaves, nobody confirms. Minimal cost, ideal for a reading the next one supersedes. QoS 1 (at least once): the receiver acknowledges, and without an acknowledgement the sender retransmits — so the same message can arrive twice and fire two n8n executions. The discipline is the one you apply to a replayed webhook: store an event identifier and skip anything already processed. QoS 2 (exactly once): four network round trips, for commands you can neither lose nor duplicate.

The retain flag asks the broker to keep a topic's last message and redeliver it to every new subscriber: n8n knows the latest temperature the second it subscribes. The flip side surprises people — on every workflow activation or restart, the Trigger receives that retained message and fires an execution, even if the sensor has published nothing for three days. The Last Will and Testament is declared by the client on connect and published by the broker on its behalf if it vanishes abruptly: that is how Zigbee2MQTT signals offline. The n8n credential exposes no will field, but a Trigger subscribed to home/+/status turns a sensor's disappearance into an alert.

The MQTT credential

  • Protocol: only three values, Mqtt, Mqtts and Ws. There is no dedicated wss entry;
  • Host and Port (1883 by default, 8883 being the TLS convention);
  • Username and Password: n8n only sends credentials if both fields are filled in. A broker configured with a username and no password will see n8n connect anonymously;
  • Clean Session, on by default; turning it off lets you receive QoS 1 and 2 messages that arrived while the client was offline;
  • Client ID: left blank, n8n generates a random one shaped like mqttjs_xxxxxxxx;
  • SSL, which reveals CA Certificates and Passwordless (certificate-based authentication), the latter unlocking Client Certificate, Client Key and Reject Unauthorized Certificate — set to false by default, so the broker certificate is not validated until you turn it on.

These values are encrypted at rest like all your API credentials. And if n8n runs in Docker with the broker on the host, localhost in Host fails with ECONNREFUSED, just like any other local service.

The MQTT node: publishing

Topic (required); Send Input Data, on by default, which publishes the input item's JSON serialised as is; Message, visible only when Send Input Data is off, for a literal payload such as ON or 21.5; plus the QoS option (Received at Most Once, Received at Least Once, Exactly Once, 0 by default) and Retain (off by default). The node publishes one message per input item, opens its connection at the start of the execution and closes it at the end, which guarantees QoS 1 and 2 acknowledgements are received. It passes its input items through unchanged, and it also works as a tool for an AI Agent.

The MQTT Trigger: subscribing

One required field, Topics, which accepts several comma-separated values, the + and # wildcards, and a per-topic QoS written after a colon:

home/lounge/temperature:1,home/+/motion,plant/line2/#:2

Without a colon the QoS is 0. Note that this syntax belongs in Topics: it is not an entry in the Options collection, which holds three. JSON Parse Body (off by default) tries to parse the payload into an object and — importantly — silently keeps the raw string if parsing fails; Only Message returns just the content, dropping the topic property; Parallel Processing, on by default, handles messages concurrently, whereas turning it off preserves order at the cost of a bottleneck. The default item:

{
  "topic": "home/lounge/temperature",
  "message": { "temperature": 21.4, "humidity": 48 }
}

Keeping topic is the right reflex with a wildcard: it is the only field telling you which room the reading came from, and the one an IF or Switch node will route on.

The critical point: the persistent connection

A webhook waits for someone to knock. An MQTT Trigger does not: on workflow activation it opens a TCP connection to the broker, subscribes, and keeps that connection alive. Three consequences.

  1. Workflow deactivated = no subscription at all. Nothing is buffered for you, unlike a RabbitMQ queue that piles messages up.
  2. n8n restart = a gap. Messages published between shutdown and reconnection are lost, unless Clean Session is off, the Client ID is fixed and the subscription runs at QoS 1 or 2: the three conditions go together.
  3. Duplicate Client ID = a reconnection war. The protocol enforces Client ID uniqueness: a client connecting with an ID already in use disconnects the other one. Two instances facing the same broker — staging and production, a blue-green switchover — sharing a credential with a fixed Client ID, and both will fight in a loop. Queue mode with Redis does not replicate the subscription across workers, but the rule stands: one distinct Client ID per instance.

The symptom is identical in all three cases: nothing happens. No failed execution, just a silent workflow. Instance monitoring paired with a heartbeat device — something publishing every minute, and a workflow that raises the alarm on its silence — remains the only reliable detection.

Throughput: one message, one execution

A sensor publishing every second means 86,400 executions per day per topic, and as many database rows. The topic overlaps with cleaning up n8n executions, except that here you can act at the source: split "measurements" and "events" topics and subscribe only to the latter, filter broker-side by subscribing to site/serverroom/alert rather than home/#, aggregate upstream (a five-minute average divides the volume by three hundred), and disable saving successful production executions in the workflow settings.

Use cases

The first reflex is the server-room alert: subscribe to site/serverroom/+, compare against thresholds, notify the on-call engineer. Then the physical button, a Zigbee button publishing to home/office/button: the cheapest webhook in the world. A Home Assistant gateway formats house events into an AI-driven Telegram bot. Historisation inserts each message through the Postgres node or into an n8n Data Table, a history an LLM can later re-read to diagnose an abnormal series. And the reverse works too: publishing a setpoint to home/lounge/setpoint based on the morning forecast.

The classic traps

  • Clean Session left on for a critical stream: any n8n outage punches a hole in the data, with no error message;
  • The infinite loop: a workflow triggered by home/# that republishes its result to home/lounge/log retriggers itself, at machine speed. Always publish to a branch you are not subscribed to — and be wary of the # wildcard, which on a broker shared with Home Assistant also captures discovery and service topics;
  • A broker with no TLS and no authentication exposed to the internet: Seyed Ali Ghazi Asgar and Narasimha Reddy, in "Analysis of Misconfigured IoT MQTT Deployments and a Lightweight Exposure Detection System" presented at the SDIoTSec workshop of NDSS 2025 (see on Google Scholar), analyse real misconfigured MQTT deployments and the attack scenarios they enable. An open broker means an attacker reading your sensors and publishing to your command topics;
  • Non-JSON payloads: Tasmota sometimes publishes ON as plain text, other devices send binary. Parsing fails silently, so test the type before a $json.message.temperature that would return undefined;
  • The retained message replayed on every activation: add a guard on the message timestamp before sending a stale alert;
  • No visible error when the connection drops: an Error Workflow will not fire, because there is no execution at all any more.

Key takeaways

Wiring MQTT into n8n takes five minutes: a credential (Protocol, Host, Port 1883, Client ID), an MQTT Trigger whose Topics field accepts commas, wildcards and a :1 QoS suffix, and an MQTT node with its QoS and Retain options. The rest comes down to three reflexes: treat QoS 1 as a source of duplicates, remember that a subscription is a living connection that dies silently, and decide up front between "subscribe to everything" and a sustainable execution budget.

Going further

A sensor alert follows the same path as an email alert: deduplicate, prioritise, enrich, route to the right person. The AI Inbox Pack (€79) applies that triage logic to an inbound stream, and it transposes directly to a noisy MQTT feed. To keep a timestamped trail of readings from a server room or a cold chain, the Compliance & Audit Pack (€149) shows how to build an audit trail that survives an inspection.

FAQ

Frequently asked questions

What is the difference between the MQTT node and the MQTT Trigger in n8n?

The MQTT Trigger is a starting node: it subscribes to one or more topics and starts an execution for every message received. The MQTT node sits in the middle or at the end of a workflow and publishes a message to a topic. The first listens to the broker, the second talks to it. A complete home-automation workflow often uses both: the Trigger catches a physical button press, and the MQTT node sends a command back to the actuator, with its QoS and Retain options.

Why does my MQTT Trigger receive the same message twice?

Because the topic is subscribed at QoS 1, which guarantees at-least-once delivery. If the acknowledgement is lost or the connection drops mid-exchange, the broker redelivers the message and n8n fires a second execution. That is normal protocol behaviour, not an n8n bug. The fix is idempotence: store a message identifier or timestamp in a tracking table and ignore an event you have already handled. QoS 2 removes the duplicate, at the cost of four network round trips.

How do I subscribe to several MQTT topics in n8n?

The MQTT Trigger's Topics field accepts several values separated by commas and supports the protocol wildcards: the plus sign replaces a single hierarchy level, the hash replaces every following level. You can also set a per-topic QoS by writing it after a colon, for example home/lounge/temperature:1,home/+/motion. Without a colon the QoS defaults to 0. A single node is therefore enough to cover a whole tree of sensors.

Should I disable Clean Session in the n8n MQTT credential?

Clean Session is enabled by default, which means the broker forgets the session on every disconnect: messages published while n8n restarts are lost for good. Disabling it asks the broker to keep the session and replay missed QoS 1 and 2 messages on reconnect. That is essential for business events, but you then need a stable Client ID, otherwise the broker cannot find the session again, and you must accept that the queue builds up broker-side during a long outage.

Bundle FlowKit Complet

€269