How To Fix Node.Js Mqtt Disconnects [Solved]

Immediate Fix

To stop Node.js MQTT disconnects caused by WiFi instability, you must implement a robust reconnection strategy in your client configuration. Relying on default settings often leads to “ghost connections” where the client thinks it is connected, but the socket is dead.

Use the following configuration snippet to ensure your client aggressively attempts to reconnect when the WiFi signal returns.


const mqtt = require('mqtt');

const options = {
  keepalive: 30,
  reconnectPeriod: 5000,
  connectTimeout: 30 * 1000,
  clean: false,
  clientId: 'nodejs_client_' + Math.random().toString(16).substr(2, 8)
};

const client = mqtt.connect('mqtt://your-broker-url', options);

client.on('error', (err) => {
  console.error('Connection error:', err);
  client.end();
});

Key Configuration Settings

Property Recommended Value Impact
keepalive 30 (seconds) Forces a ping to the broker to detect silent WiFi drops faster.
reconnectPeriod 5000 (ms) Prevents CPU spikes by waiting 5 seconds between retry attempts.
clean false Persists the session so messages aren’t lost during the drop.

Technical Explanation

In JavaScript environments, particularly on edge devices using WiFi, the TCP/IP stack may not immediately notify the Node.js runtime that a physical connection has been lost. This is known as a “half-open” connection.

When the WiFi signal fluctuates, packets are dropped. If the keepalive interval is too high, the MQTT client remains in a connected state while the underlying socket is unusable. By reducing the keep-alive and handling the offline event, you can trigger logic to buffer data locally.

Furthermore, Node.js event loops can sometimes block if you are performing heavy computation, causing the client to miss the heartbeat window. Always ensure your MQTT logic is decoupled from heavy CPU tasks.

Node.js MQTT connection stability and WiFi drop troubleshooting diagram.

Alternative Methods

If adjusting the client options does not resolve the instability, consider implementing a wrapper or using a more resilient protocol layer. WiFi drops are often physical issues that software can only mitigate, not fix entirely.

1. Use an Exponential Backoff

Instead of a fixed reconnectPeriod, you can manually call client.reconnect() with increasing delays. This prevents overwhelming the broker if an entire fleet of devices loses WiFi simultaneously.

2. Last Will and Testament (LWT)

Configure an LWT message on the broker. This allows other services in your stack to know exactly when the Node.js client has dropped off due to a network failure, allowing for automated system reboots or alerts.


# Setting LWT in options
const options = {
  will: {
    topic: 'status/device1',
    payload: 'offline',
    qos: 1,
    retain: true
  }
};

3. QoS Level 1 or 2

Increase the Quality of Service (QoS) levels for critical messages. While QoS 0 is “fire and forget,” QoS 1 ensures the message is delivered at least once, which is vital when WiFi drops are frequent and unpredictable.