Overview
Baileys manages a WebSocket connection to WhatsApp servers. Understanding the connection lifecycle, disconnect reasons, and reconnection strategies is essential for building reliable applications.Connection States
The connection can be in one of three states:Connection State Object
Fromsrc/Types/State.ts:17:
Disconnect Reasons
Fromsrc/Types/index.ts:27:
Understanding Each Reason
loggedOut(401) - User logged out from WhatsApp. Do NOT reconnect.connectionClosed(428) - Normal connection closure. Safe to reconnect.connectionLost(408) - Network issue or timeout. Reconnect.connectionReplaced(440) - Another device took over. Reconnect carefully.restartRequired(515) - Server requests restart. Reconnect immediately.timedOut(408) - Connection attempt timed out. Retry.badSession(500) - Invalid session data. May require re-authentication.multideviceMismatch(411) - Multi-device protocol mismatch. Update library.forbidden(403) - Access denied. Check credentials.unavailableService(503) - WhatsApp service temporarily unavailable.
Handling Connection Updates
Listen toconnection.update events to track connection state:
Complete Connection Example
FromExample/example.ts:40:
Reconnection Strategies
Basic Reconnection
Exponential Backoff
Smart Reconnection
QR Code Generation
When connecting for the first time, a QR code is generated:Set
printQRInTerminal: true in socket config to automatically print the QR code to the terminal.Pairing Code Flow
FromExample/example.ts:88:
Connection Configuration
Important socket configuration options for connection management:Monitoring Connection Health
Check if Connected
Presence Updates
If a desktop client is active, WhatsApp doesn’t send push notifications to the device. Mark your Baileys client as unavailable to receive notifications.
Received Pending Notifications
ThereceivedPendingNotifications flag indicates when all offline messages have been received:
History Synchronization
On first connection, WhatsApp sends message history:Best Practices
Graceful Shutdown
See Also
- Authentication - Managing auth state
- Events - Connection-related events
- WhatsApp IDs - Understanding JID format