# Dynamic broker connection - best practice

**URL:** <https://discourse.nodered.org/t/dynamic-broker-connection-best-practice/98759>\
**Category:** General\
**Tags:** mqtt\
**Created:** [21 August 2025 08:39 UTC](https://discourse.nodered.org/t/dynamic-broker-connection-best-practice/98759 "2025-08-21T08:39:19Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![bakman2](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/bakman2/32/6207_2.png) [@bakman2](https://discourse.nodered.org/u/bakman2)\
**Post date:** [21 August 2025 08:39 UTC](https://discourse.nodered.org/t/dynamic-broker-connection-best-practice/98759/1 "2025-08-21T08:39:19Z")

</div>

I want to efficiently connect and subscribe to a mqtt broker in 1 go.

I have the following in a function node:

```auto
const action = ["disconnect","connect","subscribe"]
const force = true
const topic = "zigbee2mqtt/#"
const broker = {}

broker.broker = "10.0.0.172"
broker.port = 1883
broker.username = "username"
broker.password = "pwd"

msg.broker = broker
msg.force = force
msg.topic = topic

action.forEach(action=>{
    msg.action = action
    node.send(msg)
})

return null

```

Besides the convoluted way of first connecting and then subscribing to a topic, when i push this through an mqtt node it will fail, because the connection may need to disconnect first which takes some time, so I will always be bound to some form of delay (and really I should first check for the response before continuing, which could introduce a potential loop).

Is there a simple no-nonsense way to dynamically connect/subscribe to a broker/topic.  
It would be wonderful if one could just subscribe to a topic and the dynamic subscription just assumes to disconnect/connect itself first via some option.

---

<div class="post-metadata">

**Author:** ![bakman2](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/bakman2/32/6207_2.png) [@bakman2](https://discourse.nodered.org/u/bakman2)\
**Post date:** [21 August 2025 08:42 UTC](https://discourse.nodered.org/t/dynamic-broker-connection-best-practice/98759/2 "2025-08-21T08:42:24Z")

</div>

Ok I am dumb, it already exactly does what i want: just subcribe.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)\
**Post date:** [4 September 2025 08:42 UTC](https://discourse.nodered.org/t/dynamic-broker-connection-best-practice/98759/3 "2025-09-04T08:42:49Z")

</div>

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
