nats-io/nats-server · error

received a second CONNECT packet

Error message

received a second CONNECT packet

What it means

Per the MQTT spec [MQTT-3.1.0-2], a client may send the CONNECT packet only once per connection. If a second CONNECT arrives after the session is already established, the server returns `errMQTTSecondConnectPacket` and closes the connection.

Source

Thrown at server/mqtt.go:228

var (
	sparkbNamespaceTopicPrefix    = []byte("spBv1.0/")
	sparkbCertificatesTopicPrefix = []byte("$sparkplug/certificates/")
)

var (
	mqttPingResponse     = []byte{mqttPacketPingResp, 0x0}
	mqttProtoName        = []byte("MQTT")
	mqttOldProtoName     = []byte("MQIsdp")
	mqttSessJailDur      = mqttSessFlappingJailDur
	mqttFlapCleanItvl    = mqttSessFlappingCleanupInterval
	mqttRetainedCacheTTL = mqttDefaultRetainedCacheTTL
)

var (
	errMQTTNotWebsocketPort           = errors.New("MQTT clients over websocket must connect to the Websocket port, not the MQTT port")
	errMQTTTopicFilterCannotBeEmpty   = errors.New("topic filter cannot be empty")
	errMQTTMalformedVarInt            = errors.New("malformed variable int")
	errMQTTSecondConnectPacket        = errors.New("received a second CONNECT packet")
	errMQTTServerNameMustBeSet        = errors.New("mqtt requires server name to be explicitly set")
	errMQTTUserMixWithUsersNKeys      = errors.New("mqtt authentication username not compatible with presence of users/nkeys")
	errMQTTTokenMixWIthUsersNKeys     = errors.New("mqtt authentication token not compatible with presence of users/nkeys")
	errMQTTAckWaitMustBePositive      = errors.New("ack wait must be a positive value")
	errMQTTJSAPITimeoutMustBePositive = errors.New("JS API timeout must be a positive value")
	errMQTTStandaloneNeedsJetStream   = errors.New("mqtt requires JetStream to be enabled if running in standalone mode")
	errMQTTConnFlagReserved           = errors.New("connect flags reserved bit not set to 0")
	errMQTTWillAndRetainFlag          = errors.New("if Will flag is set to 0, Will Retain flag must be 0 too")
	errMQTTPasswordFlagAndNoUser      = errors.New("password flag set but username flag is not")
	errMQTTCIDEmptyNeedsCleanFlag     = errors.New("when client ID is empty, clean session flag must be set to 1")
	errMQTTEmptyWillTopic             = errors.New("empty Will topic not allowed")
	errMQTTEmptyUsername              = errors.New("empty user name not allowed")
	errMQTTTopicIsEmpty               = errors.New("topic cannot be empty")
	errMQTTPacketIdentifierIsZero     = errors.New("packet identifier cannot be 0")
	errMQTTUnsupportedCharacters      = errors.New("character not supported for MQTT topics")
	errMQTTInvalidSession             = errors.New("invalid MQTT session")
	errMQTTInvalidRetainFlags         = errors.New("invalid retained message flags")
	errMQTTInvalidRetainedMessage     = errors.New("invalid retained message")

View on GitHub (pinned to 3a66a489d2)

Solutions

  1. Fix the client so a reconnect always opens a new TCP/WebSocket connection before sending CONNECT
  2. Ensure connect() is called at most once per established network connection
  3. Upgrade the MQTT client library if its auto-reconnect path resends CONNECT on the same socket

Example fix

// before: reuse connection on reconnect
if disconnected { client.sendConnect() }
// after: establish a fresh connection for each reconnect
if disconnected { client.dial(); client.sendConnect() }
Defensive patterns

Strategy: try-catch

Validate before calling

// Guard: never call connect() twice on one connection object
if (client.state === 'connected') return;

Try / catch

// On reconnect, always recreate the transport
client.on('close', () => setTimeout(() => newConnection().connect(), backoff))

Prevention

When it happens

Trigger: A client sending CONNECT twice on one TCP/WS connection (e.g. re-using the connection object after an auto-reconnect that did not reset the socket); buggy reconnect logic that re-sends the handshake on the existing stream (server/mqtt.go:942).

Common situations: Custom or embedded MQTT clients with flawed reconnection logic; wrapper libraries double-invoking connect; test scripts replaying captured packets.

Related errors


AI-assisted analysis of nats-io/nats-server@3a66a489d2 (2026-09-02). Data as JSON: /api/errors/3f2525c6348204a2. Report an issue: GitHub.