Skip to main content

Overview

The SocketConfig interface defines all available configuration options for a Baileys WhatsApp Web socket connection. When using makeWASocket, you pass a UserFacingSocketConfig which is Partial<SocketConfig> with a required auth property.

Type Definition

type UserFacingSocketConfig = Partial<SocketConfig> & { auth: AuthenticationState }

Configuration Properties

Connection Settings

waWebSocketUrl
string | URL
default:"'wss://web.whatsapp.com/ws/chat'"
The WebSocket URL to connect to WhatsApp Web.
waWebSocketUrl: 'wss://web.whatsapp.com/ws/chat'
connectTimeoutMs
number
default:"20000"
Fails the connection if the socket times out in this interval (milliseconds).
connectTimeoutMs: 20_000 // 20 seconds
defaultQueryTimeoutMs
number | undefined
default:"60000"
Default timeout for queries in milliseconds. Set to undefined for no timeout.
defaultQueryTimeoutMs: 60_000 // 60 seconds
keepAliveIntervalMs
number
default:"30000"
Ping-pong interval for WebSocket connection (milliseconds).
keepAliveIntervalMs: 30_000 // 30 seconds

Version & Browser

version
WAVersion
default:"[2, 3000, 1033846690]"
WhatsApp Web version to connect with. Type: [number, number, number]
import { fetchLatestBaileysVersion } from '@whiskeysockets/baileys'

const { version } = await fetchLatestBaileysVersion()
const sock = makeWASocket({ version, auth: state })
browser
WABrowserDescription
default:"Browsers.macOS('Chrome')"
Browser configuration as a tuple [OS, Browser, Version]. Use the Browsers constant for predefined configurations.
import { Browsers } from '@whiskeysockets/baileys'

// Options:
browser: Browsers.ubuntu('Chrome')
browser: Browsers.macOS('Safari')
browser: Browsers.windows('Edge')
browser: Browsers.baileys('MyApp')
browser: Browsers.appropriate('Chrome') // Based on your OS

Network & Proxy

agent
Agent
HTTPS proxy agent for the WebSocket connection.
import { Agent } from 'https'
import { HttpsProxyAgent } from 'https-proxy-agent'

const agent = new HttpsProxyAgent('http://proxy-server:8080')
const sock = makeWASocket({ agent, auth: state })
fetchAgent
Agent
Agent used for fetch requests when uploading/downloading media.
fetchAgent: new Agent({ keepAlive: true })

Logging

logger
ILogger
default:"logger.child({ class: 'baileys' })"
Logger instance for debugging and logging. Compatible with Pino logger.
import P from 'pino'

const logger = P({ level: 'debug' })
const sock = makeWASocket({ logger, auth: state })

Authentication

auth
AuthenticationState
required
Authentication state object to maintain the auth state. Use useMultiFileAuthState() to create this.
import { useMultiFileAuthState } from '@whiskeysockets/baileys'

const { state, saveCreds } = await useMultiFileAuthState('auth_info')
const sock = makeWASocket({ auth: state })

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

Events

emitOwnEvents
boolean
default:"true"
Whether events should be emitted for actions done by this socket connection.
emitOwnEvents: true // Emit events for messages you send

Media Settings

customUploadHosts
MediaConnInfo['hosts']
default:"[]"
Custom upload hosts to upload media to.
customUploadHosts: []
Width for link preview images in pixels.
linkPreviewImageThumbnailWidth: 192
Generate high quality link preview by uploading the jpegThumbnail to WhatsApp.
generateHighQualityLinkPreview: true

Retry & Error Handling

retryRequestDelayMs
number
default:"250"
Time to wait between sending new retry requests (milliseconds).
retryRequestDelayMs: 250
maxMsgRetryCount
number
default:"5"
Maximum retry count for failed messages.
maxMsgRetryCount: 5
enableAutoSessionRecreation
boolean
default:"true"
Enable automatic session recreation for failed messages.
enableAutoSessionRecreation: true
enableRecentMessageCache
boolean
default:"true"
Enable recent message caching for retry handling.
enableRecentMessageCache: true

QR Code & Pairing

qrTimeout
number
Time to wait for the generation of the next QR code in milliseconds.
qrTimeout: 60_000 // 60 seconds
printQRInTerminal
boolean
deprecated
This feature has been removed. Should the QR code be printed in the terminal.

History Sync

syncFullHistory
boolean
default:"true"
Whether Baileys should ask the phone for full history (will be received async).
syncFullHistory: true
shouldSyncHistoryMessage
(msg: proto.Message.IHistorySyncNotification) => boolean
Function to manage history processing. By default, syncs everything except FULL sync type.
shouldSyncHistoryMessage: ({ syncType }) => {
  return syncType !== proto.HistorySync.HistorySyncType.FULL
}

Initialization

fireInitQueries
boolean
default:"true"
Whether Baileys should fire init queries automatically.
fireInitQueries: true
markOnlineOnConnect
boolean
default:"true"
Marks the client as online whenever the socket successfully connects. Set to false to receive notifications in WhatsApp app.
markOnlineOnConnect: false // To receive notifications on phone

Country Code

countryCode
string
default:"'US'"
Alphanumeric country code (e.g., USA -> US) for the number used.
countryCode: 'US'

Caching

mediaCache
CacheStore
Cache to store media, so it doesn’t have to be re-uploaded.
import NodeCache from '@cacheable/node-cache'

const mediaCache = new NodeCache()
const sock = makeWASocket({ mediaCache, auth: state })
msgRetryCounterCache
CacheStore
Map to store retry counts for failed messages; used to determine whether to retry a message.
import NodeCache from '@cacheable/node-cache'

const msgRetryCounterCache = new NodeCache()
const sock = makeWASocket({ msgRetryCounterCache, auth: state })
userDevicesCache
PossiblyExtendedCacheStore
Cache to store a user’s device list.
const userDevicesCache = new NodeCache()
const sock = makeWASocket({ userDevicesCache, auth: state })
callOfferCache
CacheStore
Cache to store call offers.
const callOfferCache = new NodeCache()
const sock = makeWASocket({ callOfferCache, auth: state })
placeholderResendCache
CacheStore
Cache to track placeholder resends.
const placeholderResendCache = new NodeCache()
const sock = makeWASocket({ placeholderResendCache, auth: state })

Message Handling

shouldIgnoreJid
(jid: string) => boolean | undefined
default:"() => false"
Function that returns if a JID should be ignored. No event for that JID will be triggered and messages from that JID will not be decrypted.
import { isJidBroadcast } from '@whiskeysockets/baileys'

shouldIgnoreJid: (jid) => isJidBroadcast(jid) // Ignore broadcasts
patchMessageBeforeSending
Function
default:"msg => msg"
Optionally patch the message before sending out.
patchMessageBeforeSending: (msg, recipientJids) => {
  // Modify message before sending
  return msg
}
Full signature:
(msg: proto.IMessage, recipientJids?: string[]) => 
  Promise<PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID> |
  PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID
getMessage
(key: WAMessageKey) => Promise<proto.IMessage | undefined>
default:"async () => undefined"
Fetch a message from your store. Implement this so that messages that failed to send can be retried. This solves the “this message can take a while” issue.
getMessage: async (key) => {
  // Retrieve message from your database/store
  const msg = await db.messages.findOne({ id: key.id })
  return msg?.message
}

Group Metadata

cachedGroupMetadata
(jid: string) => Promise<GroupMetadata | undefined>
default:"async () => undefined"
Cached group metadata function to prevent redundant requests to WhatsApp and speed up message sending. Highly recommended for group usage.
import NodeCache from '@cacheable/node-cache'

const groupCache = new NodeCache({ stdTTL: 5 * 60, useClones: false })

const sock = makeWASocket({
  cachedGroupMetadata: async (jid) => groupCache.get(jid),
  auth: state
})

sock.ev.on('groups.update', async ([event]) => {
  const metadata = await sock.groupMetadata(event.id)
  groupCache.set(event.id, metadata)
})

Security & Verification

appStateMacVerification
object
default:"{ patch: false, snapshot: false }"
Verify app state MACs for enhanced security.
appStateMacVerification: {
  patch: false,
  snapshot: false
}

Signal Repository

transactionOpts
TransactionCapabilityOptions
Transaction capability options for SignalKeyStore.
transactionOpts: {
  maxCommitRetries: 10,
  delayBetweenTriesMs: 3000
}
makeSignalRepository
Function
default:"makeLibSignalRepository"
Function to create signal repository.
import { makeLibSignalRepository } from '@whiskeysockets/baileys'

makeSignalRepository: makeLibSignalRepository
Full signature:
(auth: SignalAuthState, logger: ILogger, 
 pnToLIDFunc?: (jids: string[]) => Promise<LIDMapping[] | undefined>) => 
  SignalRepositoryWithLIDStore

HTTP Options

options
RequestInit
default:"{}"
Options for HTTP fetch requests.
options: {
  headers: {
    'User-Agent': 'MyCustomAgent/1.0'
  }
}

Deprecated Options

mobile
boolean
deprecated
This feature has been removed. Should Baileys use the mobile API instead of the multi-device API.

CacheStore Interface

type CacheStore = {
  /** Get a cached key and change the stats */
  get<T>(key: string): Promise<T> | T | undefined
  /** Set a key in the cache */
  set<T>(key: string, value: T): Promise<void> | void | number | boolean
  /** Delete a key from the cache */
  del(key: string): void | Promise<void> | number | boolean
  /** Flush all data */
  flushAll(): void | Promise<void>
}

PossiblyExtendedCacheStore Interface

type PossiblyExtendedCacheStore = CacheStore & {
  mget?: <T>(keys: string[]) => Promise<Record<string, T | undefined>>
  mset?: <T>(entries: { key: string; value: T }[]) => Promise<void> | void | number | boolean
  mdel?: (keys: string[]) => void | Promise<void> | number | boolean
}

Complete Example

import makeWASocket, {
  useMultiFileAuthState,
  makeCacheableSignalKeyStore,
  fetchLatestBaileysVersion,
  Browsers
} from '@whiskeysockets/baileys'
import NodeCache from '@cacheable/node-cache'
import P from 'pino'

const logger = P({ level: 'info' })
const msgRetryCounterCache = new NodeCache()
const groupCache = new NodeCache({ stdTTL: 5 * 60, useClones: false })

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

const sock = makeWASocket({
  // Connection
  version,
  waWebSocketUrl: 'wss://web.whatsapp.com/ws/chat',
  connectTimeoutMs: 20_000,
  defaultQueryTimeoutMs: 60_000,
  keepAliveIntervalMs: 30_000,
  
  // Browser & Version
  browser: Browsers.ubuntu('MyApp'),
  
  // Auth
  auth: {
    creds: state.creds,
    keys: makeCacheableSignalKeyStore(state.keys, logger),
  },
  
  // Logging
  logger,
  
  // Events
  emitOwnEvents: true,
  
  // Retry
  retryRequestDelayMs: 250,
  maxMsgRetryCount: 5,
  msgRetryCounterCache,
  enableAutoSessionRecreation: true,
  enableRecentMessageCache: true,
  
  // History
  syncFullHistory: true,
  shouldSyncHistoryMessage: ({ syncType }) => {
    return syncType !== proto.HistorySync.HistorySyncType.FULL
  },
  
  // Media
  generateHighQualityLinkPreview: true,
  linkPreviewImageThumbnailWidth: 192,
  
  // Behavior
  markOnlineOnConnect: true,
  fireInitQueries: true,
  
  // Group metadata caching
  cachedGroupMetadata: async (jid) => groupCache.get(jid),
  
  // Message retrieval
  getMessage: async (key) => {
    // Implement message store retrieval
    return undefined
  },
  
  // Country
  countryCode: 'US',
})

// Save credentials on update
sock.ev.on('creds.update', saveCreds)

// Cache group metadata
sock.ev.on('groups.update', async ([event]) => {
  const metadata = await sock.groupMetadata(event.id)
  groupCache.set(event.id, metadata)
})

See Also

Build docs developers (and LLMs) love