Skip to main content
Baileys provides a powerful event system for intercepting and handling WebSocket frames before they’re processed by the main event handlers.

Event Callback System

The WebSocket client emits events using a special callback prefix system that allows pattern matching against binary node properties.

Callback Prefixes

All WebSocket callback events use the prefix CB: followed by a pattern:
From src/Defaults/index.ts:14:

Event Pattern Matching

The event system supports hierarchical pattern matching based on the binary node structure.

Basic Tag Matching

Match any message with a specific tag:

Attribute Matching

Match nodes with specific attribute values:

ID-Based Matching

Match messages by their unique ID attribute:

Content Tag Matching

Match based on the first child node’s tag:

Combined Matching

Combine tag, attributes, and content matching:

How Event Matching Works

From src/Socket/socket.ts:583-620, the event matching logic:

Common Event Patterns

Connection Events

Pairing & Authentication

Message Synchronization

Device & Session Management

Tag-Based Events

Besides callback events, you can listen for tag-based responses:
Baileys internally uses TAG: events with the waitForMessage() function to implement query/response patterns.

Practical Examples

Battery Monitoring

Presence Tracking

Group Metadata Changes

Call Events

Event Handler Best Practices

Avoid Memory Leaks: Always clean up event listeners when they’re no longer needed.
Error Handling: Wrap callback logic in try-catch to prevent unhandled errors from crashing your application.

Debugging Event Matching

To see which events are triggered, enable debug logging:
Unhandled messages are logged:

Complete Example

Next Steps