How to Integrate MQTT with n8n for Real-Time Automation

In today’s fast-moving digital world, automation is everywhere. From smart homes to industrial IoT systems, the need to collect, process, and react to data instantly is crucial. Whether you’re running sensors that monitor temperature, tracking device status, or sending alerts based on real-time data, automation tools can make these tasks easier and smarter.

Two tools that stand out in this landscape are MQTT and n8n. MQTT is a simple and lightweight messaging protocol designed for fast, reliable data exchange, especially in resource-limited or unreliable network environments. n8n is an open-source automation tool that lets you build workflows visually by connecting different apps and services without writing complex code.

This blog post will guide you through how to integrate MQTT with n8n, creating automated workflows that respond instantly to data published on MQTT topics. By the end, you’ll understand the basics of both technologies, how to set up your MQTT broker and n8n, and how to create workflows that make your projects more dynamic and powerful.

What is MQTT and Why Does it Matter?

MQTT, which stands for Message Queuing Telemetry Transport, is a protocol created back in the late 1990s by IBM for telemetry and sensor networks. It’s designed to be lightweight and efficient, perfect for devices with limited processing power and low bandwidth, such as microcontrollers and IoT sensors.

MQTT uses a publish/subscribe model:

  • Publishers send messages to specific topics on an MQTT broker.
  • Subscribers listen to these topics and receive messages in real time.
  • The broker acts like a post office, routing messages from publishers to subscribers.

Because MQTT keeps messages small and doesn’t require heavy connections, it’s ideal for sending quick updates like sensor readings, device states, or alerts. Many industries, from smart homes to manufacturing, rely on MQTT for real-time data.

What is n8n and Why Use It?

n8n (pronounced “n-eight-n”) is an open-source workflow automation tool. Think of it as a powerful “glue” that connects different applications and services so they can work together automatically. Unlike other automation platforms, n8n is self-hosted, giving you full control over your data and workflows.

n8n’s visual interface allows you to build workflows by dragging and dropping nodes that represent various services or actions. For example, you can create workflows that send an email when a file is uploaded to Google Drive, or post messages to Slack when a new form is submitted.

Because n8n supports custom nodes and integrations, it can connect with MQTT to react to messages coming from IoT devices or other real-time systems.

Why Integrate MQTT with n8n?

MQTT handles the real-time data delivery between devices and systems. But what if you want to take action based on those messages? For example:

  • Automatically send an alert if a temperature sensor reports a dangerously high value.
  • Store sensor data in a database for later analysis.
  • Trigger device commands when certain messages arrive.
  • Forward messages to other APIs or messaging platforms like Telegram or Slack.

This is where n8n comes in. By integrating MQTT with n8n, you create a powerful combination:

  • MQTT delivers data quickly and efficiently.
  • n8n processes data, applies logic, and automates workflows based on that data.

Together, they allow you to build event-driven systems that are responsive and flexible.

Prerequisites Before You Start

Before we dive into the integration, make sure you have the following:

  1. n8n Installed and Running
    • You can run n8n locally on your machine, use Docker, or deploy it on a cloud server.
    • Visit n8n.io for installation instructions.
  2. MQTT Broker Available
    • An MQTT broker is required to route messages between publishers and subscribers.
    • You can use Mosquitto, HiveMQ, EMQX, or a cloud MQTT service.
  3. MQTT Client
    • For testing purposes, use MQTT Explorer, MQTT.fx, or command-line clients like mosquitto_pub and mosquitto_sub.
  4. Basic Understanding of MQTT and n8n Concepts
    • Knowing what topics, subscriptions, and workflows are will help you follow along.

Setting Up Your MQTT Broker

Option 1: Installing Mosquitto Broker Locally

Mosquitto is one of the most popular MQTT brokers. It’s free, open-source, and easy to set up.

On Linux (Ubuntu/Debian):

Bash
sudo apt update
sudo apt install mosquitto mosquitto-clients
sudo systemctl start mosquitto
sudo systemctl enable mosquitto

On Windows/macOS:

  • Download the Mosquitto installer from the official Mosquitto website.
  • Follow the installation steps.
  • Start the Mosquitto service.

Testing Mosquitto:

Open two terminal windows:

  • Terminal 1: Subscribe to a topic:

Bash
mosquitto_sub -h localhost -t home/temperature
  • Terminal 2: Publish a message:

Bash
mosquitto_pub -h localhost -t home/temperature -m '{"sensor":"living_room","value":25}'

You should see the message appear in Terminal 1.

Option 2: Using a Public MQTT Broker

For quick tests, you can use brokers like test.mosquitto.org. These are open and require no setup, but be cautious about security and data privacy.

Connecting MQTT with n8n

Method 1: Using MQTT Nodes in n8n (Community Nodes)

n8n supports community-developed MQTT nodes that let you create triggers and publish messages directly in your workflow.

Step 1: Install MQTT Nodes (if needed)

If your n8n installation doesn’t have MQTT nodes by default, you may need to install them manually. Refer to the n8n community forums or documentation for the latest method.

Step 2: Configure MQTT Trigger Node

  • In n8n, add the MQTT Trigger node.
  • Fill in the broker details:
    • Host: IP address or domain of your MQTT broker.
    • Port: Usually 1883 for unencrypted MQTT.
    • Username/Password: If your broker requires authentication.
    • Topic: The MQTT topic to subscribe to, e.g., home/temperature.
  • Set the Quality of Service (QoS) (usually 0 or 1 for most cases).

This node listens for incoming MQTT messages on the specified topic.

Step 3: Connect Downstream Nodes

Once the MQTT Trigger node receives a message, you can connect other nodes for processing:

  • IF Node: Apply conditions (e.g., temperature > 28).
  • Notification Nodes: Send emails, Telegram messages, or Slack notifications.
  • Database Nodes: Save data to MySQL, PostgreSQL, or Google Sheets.
  • Function Node: Run custom JavaScript code for complex logic.

Method 2: Using Webhook and External MQTT Client

Sometimes, you might prefer to use a separate MQTT client or script to subscribe to MQTT topics and then forward messages to n8n via webhook.

Step 1: Create a Webhook in n8n

  • Add a Webhook Trigger node.
  • Copy the generated webhook URL.

Step 2: Forward MQTT Messages to the Webhook

Use a lightweight script or tool to subscribe to MQTT topics and forward data to the n8n webhook.

Example with Node.js:

JavaScript
const mqtt = require('mqtt');
const axios = require('axios');

const client = mqtt.connect('mqtt://localhost');
const webhookUrl = 'https://your-n8n-instance/webhook/your-webhook-id';

client.on('connect', () => {
  client.subscribe('home/temperature');
});

client.on('message', (topic, message) => {
  const payload = message.toString();
  axios.post(webhookUrl, { topic, payload })
    .then(res => console.log('Message forwarded'))
    .catch(err => console.error('Error forwarding message:', err));
});

This approach decouples MQTT listening from n8n but allows you to use all webhook processing features inside n8n.

Building a Real-World Example Workflow

Let’s build a practical workflow that sends an alert if the temperature in a room exceeds 28°C.

Step 1: MQTT Publisher (Sensor Simulation)

You can simulate publishing sensor data using MQTT Explorer or Mosquitto client:

Bash
mosquitto_pub -h localhost -t home/temperature -m '{"sensor":"living_room","value":29.5}'

Step 2: n8n Workflow Setup

  1. MQTT Trigger Node:
    • Subscribe to topic home/temperature.
    • Parse incoming JSON payload.
  2. IF Node:
    • Condition: Check if value > 28.
    • If true, proceed; if false, end workflow.
  3. Notification Node:
    • Send an email or Telegram message saying:"Alert! Temperature in living room is 29.5°C"
  4. Logging Node (Optional):
    • Save the message or value in a Google Sheet or database for tracking.

How to Parse MQTT Messages in n8n

MQTT messages often arrive as raw strings. To work with them:

  • Use a Set Node or Function Node after the MQTT trigger to parse JSON.

Example with Function node JavaScript code:

JavaScript
return [
  {
    json: JSON.parse(items[0].json.payload)
  }
];

This converts the payload string into a JSON object you can use in the IF node.

Testing and Verifying Your Integration

Testing your MQTT-n8n integration is critical to avoid surprises in production.

  • Publish Test Messages: Use MQTT clients to send test payloads.
  • Monitor Workflow Executions: Check n8n’s execution logs or active workflow runs.
  • Check Notifications: Confirm emails or messages are sent.
  • Review Logs or Databases: Verify data is stored as expected.

If workflows don’t trigger:

  • Double-check MQTT topic names and QoS.
  • Confirm n8n can connect to your MQTT broker.
  • Verify payload format and parsing logic.
  • Test webhook URLs (if using webhooks).

Tips and Best Practices

Security

  • Use TLS/SSL encryption to secure MQTT communication.
  • Configure username/password authentication on your broker.
  • Limit MQTT topic permissions to prevent unauthorized access.

Handling Large Message Volumes

  • Use SplitInBatches in n8n to process large datasets efficiently.
  • Implement rate limiting or buffering to avoid workflow overload.

Debugging

  • Add Code Nodes to log intermediate data.
  • Use MQTT broker logs to check connection attempts.
  • Test with simple payloads first, then increase complexity.

Scaling

  • Deploy n8n and MQTT broker on robust servers or cloud platforms.
  • Use clustering or load balancing for high availability.
  • Separate workflow responsibilities to different n8n instances if needed.

Advanced Use Cases

Smart Home Automation

Use MQTT and n8n to automate lighting, HVAC, or security based on sensor data.

Example: Turn on lights when motion is detected and it’s after sunset.

Industrial Monitoring

Track machine metrics in real-time and trigger maintenance alerts or shutdowns via n8n workflows.

Data Aggregation and Visualization

Collect MQTT data streams, store them via n8n, and forward to dashboards like Grafana for analysis.

Conclusion

Integrating MQTT with n8n unlocks the potential for powerful, real-time automation workflows. MQTT’s efficient messaging and n8n’s flexible workflow engine make a perfect pair for IoT projects, smart automation, and real-time data processing.

Whether you’re a hobbyist creating a smart home or a developer building complex IoT systems, this integration enables you to react instantly to sensor data, perform custom logic, and automate responses — all without writing heavy code.

Ready to Get Started?

  1. Set up your MQTT broker (Mosquitto is great for beginners).
  2. Install and run n8n.
  3. Build your first MQTT Trigger workflow.
  4. Experiment with real sensor data or simulations.
  5. Share your workflows and ask for help in the n8n community forum.