# MQTT connect fails on ESP32 or Arduino: PubSubClient state codes

> Read PubSubClient state codes: -2 connection failed, -4 timeout, 4 bad credentials, 5 unauthorized, and what to check for each.

Canonical: https://roboticsengineering.in/fix/mqtt-pubsubclient-connect-failed-state-codes/ | Published: 2026-11-03 | Updated: 2026-11-03

**Print client.state() after a failed connect. The number tells you where it failed.**

## What the message means

The state is -4 for a timeout, -3 for a lost connection, -2 when the network connection failed, -1 when disconnected, and 1 to 5 for refusals by the broker.

## Fix it in this order

1. State -2: check the broker address and port, and that the board is on the network. Port 1883 is the usual plain port.
2. State -4: check the network and any firewall between you and the broker.
3. State 2: the client ID was rejected. Use a unique ID for each device.
4. State 4 or 5: check the user name and password, and the access rules on the broker.
5. Call client.loop() often, and reconnect when the state is not 0.
6. Raise the buffer size with setBufferSize if large messages fail to publish.

## If you see this, do this

| You see | Do this |
| --- | --- |
| -2 on every try | Address, port or network. |
| 4 or 5 | Credentials or permissions. |

## Related

[MQTT on the ESP32](https://roboticsengineering.in/mqtt-esp32-robot-telemetry/), [Wi-Fi keeps disconnecting](https://roboticsengineering.in/fix/esp32-wifi-keeps-disconnecting/).

Last reviewed: November 2026. These are the usual causes and the order that finds them fastest. Test on your own board; clones and cables differ.
