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
Connection timeout in milliseconds. The connection fails if the socket doesn’t connect within this interval.
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.
HTTP/HTTPS proxy agent for the WebSocket connection
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 withtype WAVersion = [number, number, number]
browser
WABrowserDescription
default:"Browsers.macOS('Chrome')"
Browser identification sent to WhatsApptype WABrowserDescription = [string, string, string]
// Example: ['MyApp', 'Chrome', '1.0.0']
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' })
Whether to emit events for actions performed by this socket connection
History and sync
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
}
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 sendingtype 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.
Retry and recovery
Time to wait between sending retry requests in milliseconds
Maximum number of times to retry sending a failed message
enableAutoSessionRecreation
Enable automatic session recreation for failed messages
Enable recent message caching for retry handling
Cache stores
Cache to store media, preventing re-uploads of the same mediatype 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>
}
Cache to store retry counts for failed messages. Used to determine whether to retry a message.
userDevicesCache
PossiblyExtendedCacheStore
Cache to store user device liststype 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
}
Cache to store call offers
Cache to track placeholder resend requests
customUploadHosts
MediaConnInfo['hosts']
default:"[]"
Custom upload hosts for media uploads
linkPreviewImageThumbnailWidth
Width for link preview image thumbnails in pixels
generateHighQualityLinkPreview
Generate high-quality link previews by uploading the JPEG thumbnail to WhatsApp
Presence and status
Whether to mark the client as online when the socket successfully connects
Time to wait for the generation of the next QR code in milliseconds
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 storetype TransactionCapabilityOptions = {
maxCommitRetries: number
delayBetweenTriesMs: number
}
makeSignalRepository
function
default:"makeLibSignalRepository"
Factory function to create the Signal repositorytype 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 MACsappStateMacVerification: {
patch: boolean
snapshot: boolean
}
HTTP options
Options for HTTP fetch requests used by the socketoptions: {
headers: {
'User-Agent': 'MyApp/1.0'
}
}
Deprecated options
Deprecated: This feature has been removed. Baileys now only supports the multi-device API.
Previously used to switch between mobile and multi-device API
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