Skip to main content
Authentication utilities provide functions for managing WhatsApp authentication state, credentials storage, and signal protocol key management.

useMultiFileAuthState

Stores the full authentication state in a single folder using separate files for each credential type. More efficient than single-file storage for production use.
const useMultiFileAuthState: (
  folder: string
) => Promise<{
  state: AuthenticationState
  saveCreds: () => Promise<void>
}>

Parameters

folder
string
required
Path to the folder where authentication files will be stored. The folder will be created if it doesn’t exist.

Returns

state
AuthenticationState
The authentication state object containing credentials and key storage methods.
creds
AuthenticationCreds
Authentication credentials including noise keys, identity keys, and registration data.
keys
object
Key storage interface for Signal protocol keys.
get
function
Retrieves keys by type and IDs from storage.
set
function
Stores keys to the file system.
saveCreds
() => Promise<void>
Function to save the current credentials to disk.

Usage example

import { useMultiFileAuthState } from '@whiskeysockets/baileys'

const { state, saveCreds } = await useMultiFileAuthState('./auth_info')

const sock = makeWASocket({
  auth: state,
  // ... other options
})

// Save credentials whenever they're updated
sock.ev.on('creds.update', saveCreds)
While efficient for bots and small applications, this is not recommended for production-level use. Consider implementing a custom auth state using a SQL or NoSQL database for better scalability.

makeCacheableSignalKeyStore

Adds in-memory caching capability to a SignalKeyStore to improve performance by reducing database queries.
function makeCacheableSignalKeyStore(
  store: SignalKeyStore,
  logger?: ILogger,
  cache?: CacheStore
): SignalKeyStore

Parameters

store
SignalKeyStore
required
The base signal key store to add caching to.
logger
ILogger
Optional logger instance for tracing cache events.
cache
CacheStore
Optional custom cache store. If not provided, a default NodeCache instance with 5-minute TTL will be used.

Returns

A SignalKeyStore instance with caching capability that:
  • Checks cache before querying the underlying store
  • Automatically updates cache on writes
  • Reduces database load for frequently accessed keys

Usage example

import { makeCacheableSignalKeyStore } from '@whiskeysockets/baileys'

const { state } = await useMultiFileAuthState('./auth_info')

// Add caching to the key store
const cachedStore = makeCacheableSignalKeyStore(
  state.keys,
  logger
)

const sock = makeWASocket({
  auth: {
    creds: state.creds,
    keys: cachedStore
  }
})

initAuthCreds

Initializes a new set of authentication credentials for a fresh WhatsApp connection.
function initAuthCreds(): AuthenticationCreds

Returns

AuthenticationCreds
object
A new authentication credentials object containing:
noiseKey
KeyPair
Noise protocol key pair for encrypted communication.
pairingEphemeralKeyPair
KeyPair
Ephemeral key pair used during QR code pairing.
signedIdentityKey
KeyPair
Signed identity key for the Signal protocol.
signedPreKey
SignedKeyPair
Signed pre-key for Signal protocol key exchange.
registrationId
number
Random registration ID (0-16383).
advSecretKey
string
Base64-encoded advanced encryption secret key.
nextPreKeyId
number
Counter for the next pre-key ID (starts at 1).
firstUnuploadedPreKeyId
number
ID of the first pre-key that hasn’t been uploaded.
registered
boolean
Whether the credentials have been registered (starts as false).

Usage example

import { initAuthCreds } from '@whiskeysockets/baileys'

// Create fresh credentials
const creds = initAuthCreds()

// Use with a custom auth state implementation
const state = {
  creds,
  keys: {
    get: async (type, ids) => { /* your implementation */ },
    set: async (data) => { /* your implementation */ }
  }
}

addTransactionCapability

Adds database-like transaction capability to a SignalKeyStore for atomic operations and improved consistency.
function addTransactionCapability(
  state: SignalKeyStore,
  logger: ILogger,
  options: TransactionCapabilityOptions
): SignalKeyStoreWithTransaction

Parameters

state
SignalKeyStore
required
The base signal key store to add transaction support to.
logger
ILogger
required
Logger instance for transaction events.
options
TransactionCapabilityOptions
required
Transaction configuration options.
maxCommitRetries
number
Maximum number of retry attempts for failed commits.
delayBetweenTriesMs
number
Delay in milliseconds between retry attempts.

Returns

A SignalKeyStoreWithTransaction that extends SignalKeyStore with:
  • transaction(work, key) - Execute work within a transaction
  • isInTransaction() - Check if currently in a transaction context

Usage example

import { addTransactionCapability } from '@whiskeysockets/baileys'

const storeWithTx = addTransactionCapability(
  baseStore,
  logger,
  {
    maxCommitRetries: 3,
    delayBetweenTriesMs: 200
  }
)

// Use transactions for atomic operations
await storeWithTx.transaction(async () => {
  // All operations here are atomic
  await storeWithTx.set({
    'pre-key': { '1': preKey1, '2': preKey2 },
    'session': { '[email protected]': session }
  })
}, 'unique-transaction-key')

BufferJSON

Utility object for JSON serialization and deserialization of Buffer objects.
const BufferJSON = {
  replacer: (key: any, value: any) => any
  reviver: (key: any, value: any) => any
}

Properties

replacer
function
JSON.stringify replacer function that converts Buffer objects to base64-encoded objects.
reviver
function
JSON.parse reviver function that converts base64-encoded objects back to Buffers.

Usage example

import { BufferJSON } from '@whiskeysockets/baileys'

const data = {
  name: 'test',
  buffer: Buffer.from('hello world')
}

// Serialize with Buffer support
const json = JSON.stringify(data, BufferJSON.replacer)

// Deserialize back to original form
const restored = JSON.parse(json, BufferJSON.reviver)
console.log(Buffer.isBuffer(restored.buffer)) // true
The BufferJSON utility is particularly useful when persisting authentication state to JSON files, as it handles the serialization of cryptographic keys and other binary data.

generateRegistrationId

Generates a random registration ID for WhatsApp authentication.
function generateRegistrationId(): number

Returns

A random number between 0 and 16383 (14-bit value) used as the registration ID.

Usage example

import { generateRegistrationId } from '@whiskeysockets/baileys'

const regId = generateRegistrationId()
console.log(regId) // e.g., 8472
  • AuthenticationState - Complete authentication state structure
  • AuthenticationCreds - Credential data structure
  • SignalKeyStore - Interface for storing Signal protocol keys
  • SignalKeyStoreWithTransaction - Extended interface with transaction support
  • SignalDataTypeMap - Mapping of signal data types to their value types

Build docs developers (and LLMs) love