Skip to main content

Overview

Baileys uses an EventEmitter-based system to notify your application of WhatsApp events like new messages, connection changes, and contact updates. All events are strongly typed through the BaileysEventMap interface.

BaileysEventMap

From src/Types/Events.ts:20:

Event Emitter Interface

From src/Types/Events.ts:154:

Basic Event Handling

Single Event Listener

Multiple Event Listeners

Event Processing Pattern

Baileys provides ev.process() for batch event processing. From Example/example.ts:70:
Using ev.process() is more efficient than individual listeners when handling multiple related events, as it batches updates together.

Message Events

messages.upsert

Fired when new messages arrive or are added to history:
Always use a loop when handling messages.upsert as the messages array can contain multiple messages.

messages.update

Fired when message status changes (delivered, read, deleted, edited):

messages.reaction

Fired when a message receives a reaction:

messages.delete

Fired when messages are deleted:

Chat Events

chats.upsert

chats.update

Contact Events

contacts.upsert

contacts.update

From Example/example.ts:204:

Group Events

group-participants.update

groups.update

Presence Events

Call Events

History Sync Events

From Example/example.ts:119:

Event Order on First Connection

  1. connection.update - Connection state changes to ‘connecting’
  2. connection.update - QR code received (if not authenticated)
  3. connection.update - Connection opens
  4. creds.update - Credentials updated
  5. messaging-history.set - Message history received
  6. chats.upsert - Chats loaded
  7. contacts.upsert - Contacts loaded
  8. connection.update - receivedPendingNotifications: true

Removing Event Listeners

Best Practices

Event Handling Best Practices:
  1. Use ev.process() - Batch related events for efficiency
  2. Handle errors - Wrap handlers in try-catch blocks
  3. Async handlers - Use async/await for async operations
  4. Loop messages - Always iterate messages array in messages.upsert
  5. Save credentials - Always handle creds.update to save auth state
  6. Avoid blocking - Don’t block event handlers with long operations
  7. Clean up listeners - Remove listeners when done to prevent memory leaks

Error Handling

TypeScript Type Safety

Baileys provides full TypeScript support for events:

See Also