Skip to main content

Overview

The SocketConfig interface defines all configuration options for creating a WhatsApp socket connection. When using makeWASocket, you provide a UserFacingSocketConfig, which is a partial version with only auth required.

Type definition

type UserFacingSocketConfig = Partial<SocketConfig> & { 
  auth: AuthenticationState 
}
All properties except auth are optional and will use sensible defaults from DEFAULT_CONNECTION_CONFIG.

Connection settings

waWebSocketUrl
string | URL
default:"'wss://web.whatsapp.com/ws/chat'"
The WebSocket URL to connect to WhatsApp
connectTimeoutMs
number
default:"20000"
Connection timeout in milliseconds. The connection fails if the socket doesn’t connect within this interval.
keepAliveIntervalMs
number
default:"30000"
Ping-pong interval for WebSocket connection in milliseconds
defaultQueryTimeoutMs
number | undefined
default:"60000"
Default timeout for queries in milliseconds. Set to undefined for no timeout.
agent
Agent
HTTP/HTTPS proxy agent for the WebSocket connection
fetchAgent
Agent
Agent used for fetch requests when uploading/downloading media

Authentication

auth
AuthenticationState
required
Authentication state object containing credentials and signal keys. See AuthenticationState for details.
type AuthenticationState = {
  creds: AuthenticationCreds
  keys: SignalKeyStore
}

Client identification

version
WAVersion
default:"[2, 3000, 1033846690]"
WhatsApp Web version to connect with
type WAVersion = [number, number, number]
browser
WABrowserDescription
default:"Browsers.macOS('Chrome')"
Browser identification sent to WhatsApp
type WABrowserDescription = [string, string, string]
// Example: ['MyApp', 'Chrome', '1.0.0']
countryCode
string
default:"'US'"
Alphanumeric country code for the phone number (e.g., ‘US’, ‘GB’, ‘IN’)

Logging and events

logger
ILogger
default:"logger.child({ class: 'baileys' })"
Logger instance for debug and error logging. Baileys uses Pino-compatible loggers.
import pino from 'pino'

const logger = pino({ level: 'debug' })
emitOwnEvents
boolean
default:"true"
Whether to emit events for actions performed by this socket connection

History and sync

syncFullHistory
boolean
default:"true"
Whether Baileys should request full chat history from the phone. History is received asynchronously.
shouldSyncHistoryMessage
(msg: proto.Message.IHistorySyncNotification) => boolean
Function to determine which history messages should be synced. By default, syncs everything except FULL type.
// Default implementation
shouldSyncHistoryMessage: ({ syncType }) => {
  return syncType !== proto.HistorySync.HistorySyncType.FULL
}
fireInitQueries
boolean
default:"true"
Whether Baileys should automatically fire initialization queries on connection

Message handling

getMessage
(key: WAMessageKey) => Promise<proto.IMessage | undefined>
default:"async () => undefined"
Function to fetch a message from your storage. Implement this to enable message retry for failed sends.
getMessage: async (key) => {
  return await db.messages.findOne({ 
    id: key.id,
    remoteJid: key.remoteJid 
  })
}
patchMessageBeforeSending
function
default:"msg => msg"
Function to optionally patch messages before sending
type PatchFunction = (
  msg: proto.IMessage,
  recipientJids?: string[]
) => Promise<PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID>
   | PatchedMessageWithRecipientJID[] 
   | PatchedMessageWithRecipientJID
shouldIgnoreJid
(jid: string) => boolean | undefined
default:"() => false"
Function to determine if a JID should be ignored. No events will be triggered for ignored JIDs, and messages from them won’t be decrypted.
shouldIgnoreJid: (jid) => {
  return jid === '[email protected]'
}

Retry and recovery

retryRequestDelayMs
number
default:"250"
Time to wait between sending retry requests in milliseconds
maxMsgRetryCount
number
default:"5"
Maximum number of times to retry sending a failed message
enableAutoSessionRecreation
boolean
default:"true"
Enable automatic session recreation for failed messages
enableRecentMessageCache
boolean
default:"true"
Enable recent message caching for retry handling

Cache stores

mediaCache
CacheStore
Cache to store media, preventing re-uploads of the same media
type CacheStore = {
  get<T>(key: string): Promise<T> | T | undefined
  set<T>(key: string, value: T): Promise<void> | void | number | boolean
  del(key: string): void | Promise<void> | number | boolean
  flushAll(): void | Promise<void>
}
msgRetryCounterCache
CacheStore
Cache to store retry counts for failed messages. Used to determine whether to retry a message.
userDevicesCache
PossiblyExtendedCacheStore
Cache to store user device lists
type PossiblyExtendedCacheStore = CacheStore & {
  mget?: <T>(keys: string[]) => Promise<Record<string, T | undefined>>
  mset?: <T>(entries: { key: string; value: T }[]) => Promise<void> | void
  mdel?: (keys: string[]) => void | Promise<void> | number | boolean
}
callOfferCache
CacheStore
Cache to store call offers
placeholderResendCache
CacheStore
Cache to track placeholder resend requests

Media and previews

customUploadHosts
MediaConnInfo['hosts']
default:"[]"
Custom upload hosts for media uploads
Width for link preview image thumbnails in pixels
Generate high-quality link previews by uploading the JPEG thumbnail to WhatsApp

Presence and status

markOnlineOnConnect
boolean
default:"true"
Whether to mark the client as online when the socket successfully connects
qrTimeout
number
Time to wait for the generation of the next QR code in milliseconds

Group metadata

cachedGroupMetadata
(jid: string) => Promise<GroupMetadata | undefined>
default:"async () => undefined"
Function to retrieve cached group metadata. Prevents redundant requests to WhatsApp and speeds up message sending.
cachedGroupMetadata: async (jid) => {
  return await db.groups.findOne({ jid })
}

Signal protocol

transactionOpts
TransactionCapabilityOptions
Transaction options for the Signal key store
type TransactionCapabilityOptions = {
  maxCommitRetries: number
  delayBetweenTriesMs: number
}
makeSignalRepository
function
default:"makeLibSignalRepository"
Factory function to create the Signal repository
type MakeSignalRepository = (
  auth: SignalAuthState,
  logger: ILogger,
  pnToLIDFunc?: (jids: string[]) => Promise<LIDMapping[] | undefined>
) => SignalRepositoryWithLIDStore

App state verification

appStateMacVerification
object
default:"{ patch: false, snapshot: false }"
Options to verify app state MACs
appStateMacVerification: {
  patch: boolean
  snapshot: boolean
}

HTTP options

options
RequestInit
default:"{}"
Options for HTTP fetch requests used by the socket
options: {
  headers: {
    'User-Agent': 'MyApp/1.0'
  }
}

Deprecated options

mobile
boolean
Deprecated: This feature has been removed. Baileys now only supports the multi-device API.
Previously used to switch between mobile and multi-device API
printQRInTerminal
boolean
Deprecated: This feature has been removed.
Previously used to automatically print QR codes in the terminal

Example configuration

import makeWASocket, { 
  DisconnectReason,
  useMultiFileAuthState,
  Browsers 
} from '@whiskeysockets/baileys'
import pino from 'pino'
import NodeCache from 'node-cache'

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

// Create caches
const msgRetryCache = new NodeCache()
const userDevicesCache = new NodeCache()

const sock = makeWASocket({
  // Authentication (required)
  auth: state,
  
  // Connection
  connectTimeoutMs: 60_000,
  defaultQueryTimeoutMs: 60_000,
  keepAliveIntervalMs: 30_000,
  
  // Client identification
  browser: Browsers.ubuntu('MyApp'),
  countryCode: 'US',
  
  // Logging
  logger: pino({ level: 'info' }),
  emitOwnEvents: true,
  
  // Sync settings
  syncFullHistory: false,
  fireInitQueries: true,
  markOnlineOnConnect: true,
  
  // Message handling
  getMessage: async (key) => {
    return await database.getMessage(key)
  },
  
  // Caching
  msgRetryCounterCache: msgRetryCache,
  userDevicesCache: userDevicesCache,
  
  // Group metadata
  cachedGroupMetadata: async (jid) => {
    return await database.getGroupMetadata(jid)
  },
  
  // Custom message patching
  patchMessageBeforeSending: (msg, recipientJids) => {
    // Add custom logic here
    return msg
  },
  
  // Ignore specific JIDs
  shouldIgnoreJid: (jid) => {
    return blockedJids.includes(jid)
  },
  
  // History sync filtering
  shouldSyncHistoryMessage: ({ syncType }) => {
    return syncType !== proto.HistorySync.HistorySyncType.FULL
  },
  
  // Retry configuration
  retryRequestDelayMs: 250,
  maxMsgRetryCount: 5,
  
  // Media settings
  generateHighQualityLinkPreview: true,
  linkPreviewImageThumbnailWidth: 192
})

sock.ev.on('creds.update', saveCreds)

Default values

All default values are defined in DEFAULT_CONNECTION_CONFIG:
export const DEFAULT_CONNECTION_CONFIG: SocketConfig = {
  version: [2, 3000, 1033846690],
  browser: Browsers.macOS('Chrome'),
  waWebSocketUrl: 'wss://web.whatsapp.com/ws/chat',
  connectTimeoutMs: 20_000,
  keepAliveIntervalMs: 30_000,
  logger: logger.child({ class: 'baileys' }),
  emitOwnEvents: true,
  defaultQueryTimeoutMs: 60_000,
  customUploadHosts: [],
  retryRequestDelayMs: 250,
  maxMsgRetryCount: 5,
  fireInitQueries: true,
  markOnlineOnConnect: true,
  syncFullHistory: true,
  patchMessageBeforeSending: msg => msg,
  shouldSyncHistoryMessage: ({ syncType }) => {
    return syncType !== proto.HistorySync.HistorySyncType.FULL
  },
  shouldIgnoreJid: () => false,
  linkPreviewImageThumbnailWidth: 192,
  transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 3000 },
  generateHighQualityLinkPreview: false,
  enableAutoSessionRecreation: true,
  enableRecentMessageCache: true,
  options: {},
  appStateMacVerification: {
    patch: false,
    snapshot: false
  },
  countryCode: 'US',
  getMessage: async () => undefined,
  cachedGroupMetadata: async () => undefined,
  makeSignalRepository: makeLibSignalRepository
}

See also

Build docs developers (and LLMs) love