Skip to main content
Baileys uses WhatsApp’s binary protocol for efficient communication. This guide explains the protocol structure and how messages are encoded/decoded.

Binary Protocol Overview

WhatsApp uses a custom binary protocol instead of plain XML to reduce bandwidth and improve performance. Messages are encoded as binary nodes with a compact token-based encoding system.

Key Components

  • Binary Nodes: Structured data units with tags, attributes, and content
  • Token Dictionary: Predefined tokens for common strings
  • Binary Encoding: Efficient byte-level encoding
  • Compression: Optional frame compression

Binary Node Structure

From src/WABinary/types.ts:9-13:

Components

Tag: Identifies the node type
Attributes: Key-value metadata
Content: Can be nested nodes, strings, or binary data

Token-Based Encoding

To reduce message size, WhatsApp uses a dictionary of predefined tokens for common strings.

Token Types

From src/WABinary/constants.ts:1-19:

Single-Byte Tokens

Common strings encoded as single bytes (0-235):
Example: The string "type" is encoded as byte 4 instead of 4 bytes.

Double-Byte Tokens

Less common strings use two bytes (dictionary index + token index):

Encoding Process

From src/WABinary/encode.ts:5-12:

Encoding Steps

  1. Write list header - Number of elements (tag + attributes + content)
  2. Write tag - Encoded as token or raw string
  3. Write attributes - Each key-value pair encoded
  4. Write content - Recursively encode based on type

String Encoding

From src/WABinary/encode.ts:179-209:

Packed Encoding

Nibble Packing: Stores numbers and special chars (-, .) as 4-bit values
Hex Packing: Stores hex strings (0-9, A-F) efficiently

JID Encoding

WhatsApp IDs (JIDs) are specially encoded:

Decoding Process

From src/WABinary/decode.ts:9-18:

Decoding Steps

  1. Decompress - If compression flag is set
  2. Read list size - Number of elements
  3. Read tag - First element is always the tag
  4. Read attributes - Pairs of key-value strings
  5. Read content - If list size is even, read content
From src/WABinary/decode.ts:251-296:

Frame Format

WhatsApp frames are wrapped with: From src/Defaults/index.ts:34:

Compression

Frames can be optionally compressed using zlib:

Common Node Examples

Query Node

This queries the server for pre-key count.

Message Node

Presence Node

Working with Binary Nodes

Creating Nodes

Parsing Nodes

Extracting Content

Converting to String (Debug)

Protocol Constants

From src/Defaults/index.ts:

Best Practices

Use Helper Functions: Baileys provides utilities for working with binary nodes. Use them instead of manual parsing.
Type Safety: Always check content types before accessing:

Debugging Tools

Enable trace logging to see binary node XML representations:
Output example:

Learn More

To understand the underlying cryptography:
  • Libsignal Protocol: End-to-end encryption protocol
  • Noise Protocol Framework: Handshake patterns and session keys

Next Steps