MQTT code generator
Pick a broker, transport and topics, and get a complete, runnable MQTT client in Python, Node.js, browser JavaScript, ESP32/Arduino, Go, Java, C# or the mosquitto command line — connect, subscribe and publish in one copy-paste.
Generated code
Open in online clientimport uuid
import paho.mqtt.client as mqtt
BROKER = "broker.connectmq.com"
PORT = 1883
SUB_TOPIC = "testmqtt/demo/#"
PUB_TOPIC = "testmqtt/demo/hello"
PAYLOAD = "Hello from TestMQTT"
QOS = 1
CLIENT_ID = f"python-{uuid.uuid4().hex[:8]}"
def on_connect(client, userdata, flags, reason_code, properties):
if reason_code.is_failure:
print(f"Connection failed: {reason_code}")
return
print(f"Connected to {BROKER}:{PORT}")
# Subscribing here means the subscription is renewed after every reconnect.
client.subscribe(SUB_TOPIC, qos=QOS)
client.publish(PUB_TOPIC, PAYLOAD, qos=QOS)
def on_message(client, userdata, msg):
print(f"{msg.topic}: {msg.payload.decode(errors='replace')}")
def on_disconnect(client, userdata, flags, reason_code, properties):
print(f"Disconnected: {reason_code}")
client = mqtt.Client(
mqtt.CallbackAPIVersion.VERSION2,
client_id=CLIENT_ID,
protocol=mqtt.MQTTv311,
transport="tcp",
)
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.connect(BROKER, PORT, keepalive=60)
client.loop_forever() # blocks; handles reconnects. Stop with Ctrl+CHow the generated code works
Every snippet follows the same flow: open a connection to the broker, subscribe to your topic once the connection is acknowledged, publish one message, then keep running and print everything that arrives. Subscribing inside the connect handler (where the library has one) matters more than it looks — it means subscriptions are restored automatically after a reconnect. Leave the client ID empty and each program generates a random one at runtime, so two copies never kick each other off the broker.
The transport decides the URL scheme. Plain TCP usually runs on port 1883 and TLS on 8883, while WebSocket listeners vary by broker — that is why the port and path are filled in from the preset. See the MQTT ports guide for the full list of conventions.
Why these libraries
- Python — paho-mqtt 2.x. The reference Eclipse client, stable for over a decade. Version 2 changed the callback signatures, so older tutorials break; this code targets the new
VERSION2API. More in MQTT with Python. - Node.js and browser — MQTT.js v5. One library for both runtimes, with promise-based methods such as
connectAsyncandpublishAsync. In the browser it connects over WebSockets only; read MQTT in JavaScript and MQTT over WebSockets. - ESP32 / Arduino — PubSubClient. Tiny, battle-tested and available in the Library Manager. It speaks MQTT 3.1.1 over TCP or TLS and publishes at QoS 0. The ESP32 MQTT guide covers Wi-Fi reconnects and certificates.
- Go — paho.mqtt.golang. The most widely deployed Go client, with auto-reconnect and WebSocket support built in. It implements MQTT 3.1.1; use
paho.golangfor MQTT 5. - Java — Eclipse Paho v3. The synchronous
MqttClientkeeps the example short; switch toMqttAsyncClientor the Paho v5 client for production services. - C# — MQTTnet v4. The de facto .NET MQTT library, fully async and supporting MQTT 5. The code uses .NET 6+ top-level statements.
- Command line — mosquitto_pub / mosquitto_sub. The fastest way to prove a broker works before writing any code. See the mosquitto_pub and mosquitto_sub examples.
Quick notes per language
TLS: the Python, Node.js, Go, Java and C# snippets verify the broker certificate against the operating system’s trusted CAs, which works for brokers with a public certificate. On the ESP32 the sample calls setInsecure() to get you connected; load the broker’s root CA with setCACert() before shipping devices. Self-signed brokers need the CA file passed explicitly in every language.
MQTT 5: Python, MQTT.js, MQTTnet and the mosquitto CLI switch protocol with one option. PubSubClient, paho.mqtt.golang and Paho Java v3 stay on MQTT 3.1.1 — which every MQTT 5 broker still accepts.
Testing: run the generated program and watch the same topic in the online MQTT client. If nothing arrives, the broker testing checklist walks through ports, credentials and topic typos step by step. Remember that on a public broker anyone can read your topics — keep real data on a broker with authentication.
MQTT code generator FAQ
Which MQTT library should I use for Python?
Eclipse Paho (paho-mqtt) is the most widely used Python MQTT client. Version 2.x requires a callback API version when creating the client; the generated code uses CallbackAPIVersion.VERSION2, which works for both MQTT 3.1.1 and MQTT 5.
Why does the browser code only work with WebSockets?
Web pages cannot open raw TCP sockets, so browser MQTT clients tunnel MQTT through a WebSocket connection. Your broker needs a WebSocket listener, and pages served over HTTPS must use a secure wss:// URL.
Can an ESP32 use MQTT over WebSockets?
Not with PubSubClient, the most common Arduino MQTT library — it only supports plain TCP and TLS. That is rarely a limitation: the ESP32 can open TCP and TLS sockets directly, which are lighter than WebSockets anyway.
Is it safe to put my broker password in the generated code?
The code is generated in your browser and never sent to a server. Still, avoid committing passwords to source control: load them from environment variables or a secrets file, and never ship admin credentials in browser JavaScript.