Overview
Baileys uses WhatsApp’s multi-device protocol for authentication. The library manages authentication state through credentials and cryptographic keys that enable secure communication with WhatsApp servers.Authentication State
The authentication state consists of two primary components:1. Credentials (AuthenticationCreds)
Credentials contain identity information and cryptographic material:
2. Signal Keys (SignalKeyStore)
The key store manages cryptographic keys used for message encryption:
pre-key- Pre-keys for establishing sessionssession- Active session datasender-key- Group encryption keysapp-state-sync-key- App state synchronization keysidentity-key- Identity verification keys
Using Multi-File Auth State
Baileys providesuseMultiFileAuthState for file-based credential storage:
How It Works
The multi-file auth state:- Stores credentials in
creds.json - Stores keys in separate files:
{type}-{id}.json - Uses file locks to prevent race conditions
- Serializes buffers using
BufferJSONfor safe JSON storage
src/Utils/use-multi-file-auth-state.ts:33:
QR Code Authentication
Connect by scanning a QR code with WhatsApp:Pairing Code Authentication
Connect using a pairing code instead of QR:The phone number must include the country code and contain only digits (no
+, (), or -).Initializing Credentials
When no credentials exist, Baileys generates new ones usinginitAuthCreds():
From src/Utils/auth-utils.ts:346:
Caching Signal Keys
For better performance, usemakeCacheableSignalKeyStore to cache frequently accessed keys:
Key Management
TheuseMultiFileAuthState function automatically handles this, but custom implementations must be careful:
Account Settings
Credentials include account-level settings:Best Practices
BufferJSON Serialization
When storing auth state as JSON, use theBufferJSON utility for proper Buffer serialization:
See Also
- Connection Lifecycle - Managing socket connections
- Events - Handling authentication events
- WhatsApp IDs - Understanding JID format