Skip to main content

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

From src/Types/State.ts:17:

Disconnect Reasons

From src/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 to connection.update events to track connection state:

Complete Connection Example

From Example/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

From Example/example.ts:88:

Connection Configuration

Important socket configuration options for connection management:
If markOnlineOnConnect is true, your phone won’t receive notifications while Baileys is connected. Set to false if you want to receive notifications on your phone.

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

The receivedPendingNotifications flag indicates when all offline messages have been received:

History Synchronization

On first connection, WhatsApp sends message history:

Best Practices

Connection Management Tips:
  1. Always check loggedOut - Never reconnect when user logged out
  2. Implement backoff - Use exponential backoff for reconnection attempts
  3. Save credentials - Listen to creds.update and save immediately
  4. Handle QR expiry - QR codes expire; generate new ones
  5. Monitor health - Track connection state and last disconnect reason
  6. Graceful shutdown - Properly close the socket before exiting
  7. Log errors - Log lastDisconnect.error for debugging

Graceful Shutdown

See Also