Skip to Content
API Reference

API Reference

A grouped, quick-lookup index of every public export from the zaileys package. Everything below is re-exported from the package root, so a single import works for any symbol:

import { Client, MessageBuilder, SqliteAuthStore, SqliteMessageStore } from 'zaileys'

This page is a terse exports index. For full prose, options tables, and end-to-end examples follow the deep-links to the relevant guide page on each entry.

Client

The main entry point. See Client & Lifecycle and Configuration.

import { Client, MemoryAuthStore, MemoryMessageStore } from 'zaileys' const client = new Client({ sessionId: 'main', auth: new MemoryAuthStore(), store: new MemoryMessageStore(), authType: 'qr', qrTerminal: true, }) client.on('connect', ({ me }) => console.log('connected as', me.id)) client.on('text', (ctx) => { if (ctx.text === 'ping') ctx.reply('pong') })
MemberSignatureDescription
new Client(opts?)(options?: ClientOptions)Construct a client; auto-connects unless autoConnect: false.
connect()(): Promise<void>Open the WhatsApp connection (QR or pairing).
disconnect()(): Promise<void>Close the socket without clearing auth.
logout()(): Promise<void>Log out and clear stored credentials.
get stateConnectionStateCurrent state (idle | connecting | connected | disconnected).
get socketBaileysSocket | undefinedUnderlying socket (escape hatch).
send(to)(to: string): MessageBuilder<'init'>Start a fluent message builder for a JID. See Sending Messages.
edit(key)(key: WAMessageKey): EditBuilderEdit a previously sent message.
delete(key, opts?)(key, opts?: DeleteOptions): Promise<void>Delete a message.
react(key, emoji)(key, emoji: string): Promise<WAMessageKey>React to a message.
forward(key, to)(key, to: string): Promise<WAMessageKey>Forward a message to a JID.
pin(key, opts?)(key, opts?: { duration?: number }): Promise<WAMessageKey>Pin a message (duration seconds; defaults 86400).
unpin(key)(key): Promise<WAMessageKey>Unpin a message.
setDisappearing(jid, seconds)(jid: string, seconds: number): Promise<void>Set the chat’s disappearing-message timer.
rejectCall(call | callId, from?)(call: CallPayload | string, from?: string): Promise<void>🔗 Reject an incoming call. Accepts the call-incoming payload or raw callId + caller jid. Throws UNSUPPORTED_ON_CLOUD on the cloud provider. See autoRejectCall.
lidToPn(lid)(lid: string): Promise<string | null>Resolve a @lid JID to its phone-number JID (null if unknown). Needs a connected socket.
pnToLid(pn)(pn: string): Promise<string | null>Resolve a phone-number JID to its @lid JID (null if unknown). Needs a connected socket.
broadcast(jids, build, opts?)(jids: string[], build, opts?): Promise<BroadcastResult>Send to many recipients. See Broadcast & Schedule.
scheduleAt(date, build, opts?)(date: Date, build, opts?): Promise<ScheduleHandle>Schedule a message for later.
command(spec, handler)(spec: string, handler: CommandHandler): thisRegister a command. See Commands.
use(middleware)(middleware: Middleware): thisAdd command middleware.
get groupGroupModuleGroup management.
get privacyPrivacyModulePrivacy & blocking.
get newsletterNewsletterModuleNewsletter/channel management.
get communityCommunityModuleCommunity management.
get profileProfileModuleOwn profile name/status/picture.
get chatChatModuleChat archive/pin/mute/read/star/delete.
get contactContactModuleContact check/exists/save/remove.
get businessBusinessModuleBusiness profile & catalog/products.
get presencePresenceModulePresence updates.
on/once/off/emitinherited from TypedEventEmitterTyped event subscription. See Events.

Related client exports: TypedEventEmitter, TypedEventEmitterOptions.

Configuration Types

Types backing the Client constructor. See Configuration.

ExportKindDescription
ClientOptionsinterfaceAll constructor options (sessionId, auth, store, authType, phoneNumber, logger, cacheSignal, reconnect, qrTerminal, baileys, autoConnect, statusLog, commandPrefix, citation, ignoreMe).
ConnectionStatetypeidle | connecting | connected | disconnected (and reconnecting states).
ConnectionAuthTypetype'qr' | 'pairing'.
ReconnectOptionsinterfaceReconnect backoff configuration.
LoggerinterfacePluggable logger contract.
ClientEventMap / ClientEventNametypeFull event map (connection + inbound).
ConnectionEventMap / ConnectionEventName / ConnectionEventHandlertypeConnection-only event types.
BaileysSockettypeAlias for the underlying WASocket.

Auth Stores

Credential persistence. Pass an instance to Client’s auth option. See Storage Adapters.

import { Client, SqliteAuthStore } from 'zaileys' const client = new Client({ sessionId: 'main', auth: new SqliteAuthStore({ path: './session.db' }), })
ExportKindDescription
MemoryAuthStoreclassIn-memory creds (non-persistent).
FileAuthStoreclassFile-based store. Options: FileAuthStoreOptions.
SqliteAuthStoreclassSQLite-backed. Options: SqliteAuthStoreOptions.
PostgresAuthStoreclassPostgres-backed. Options: PostgresAuthStoreOptions.
RedisAuthStoreclassRedis-backed. Options: RedisAuthStoreOptions.
ConvexAuthStoreclassConvex-backed. Options: ConvexAuthStoreOptions.
makeCacheableAuthStore(...)functionWrap a store with an in-memory cache. Options: CacheableAuthStoreOptions.
AuthStoreBundleinterface{ creds: AuthCredsStore; signal: AuthStore } — the contract all adapters implement.
AuthStore / AuthCredsStoreinterfaceSignal-key and credential sub-stores.
AuthStoreKey / AuthStoreValuetypeSignal data key/value types.

Message Stores

Chat/message/contact/presence persistence. Pass to Client’s store option. See Storage Adapters.

ExportKindDescription
MemoryMessageStoreclassIn-memory message store.
SqliteMessageStoreclassSQLite-backed. Options: SqliteMessageStoreOptions.
PostgresMessageStoreclassPostgres-backed. Options: PostgresMessageStoreOptions.
RedisMessageStoreclassRedis-backed. Options: RedisMessageStoreOptions.
ConvexMessageStoreclassConvex-backed. Options: ConvexMessageStoreOptions.
MessageStoreinterfaceStore contract: saveMessage, getMessage, listMessages, saveChat, getChat, listChats, saveContact, getContact, listContacts, savePresence, getPresence, bind, clear, close, optional saveScheduledJob/listScheduledJobs/deleteScheduledJob.
MessageStoreListOptionstypePagination/filter options for listMessages.
ScheduledJobRecordtypePersisted scheduled-job row.
BaileysSocketLikeinterfaceMinimal socket shape consumed by MessageStore.bind.

Builder (Sending Messages)

Fluent message construction. See Sending Messages, Interactive Messages, Rich Responses.

client .send('628xxx@s.whatsapp.net') .text('Hello *world*') .reply(msg.message().key)

MessageBuilder<State>

MethodSignatureDescription
to(recipient)(recipient: string): MessageBuilder<'init'>Set recipient JID.
text(content, opts?)(content: string, opts?: TextOptions): MessageBuilder<'content-set'>Text message (opts.rich enables AIRich).
image(src, opts?)(src: MediaSource, opts?: ImageOptions)Image.
video(src, opts?)(src: MediaSource, opts?: VideoOptions)Video.
videoNote(src, opts?)(src: MediaSource, opts?: VideoNoteOptions)Round video note (PTV).
audio(src, opts?)(src: MediaSource, opts?: AudioOptions)Audio / voice note.
document(src, opts)(src: MediaSource, opts: DocumentOptions)Document.
sticker(src, opts?)(src: MediaSource, opts?: StickerOptions)Sticker.
buttons(...)interactive button messageSee Interactive.
carousel(...)carousel/cardsSee Interactive.
list(opts)(opts: ListOptions)List message.
poll(...)poll message (PollOptions)See Interactive.
location(...)location (LocationOptions)Share location.
contact(vcard)(vcard: string)Share a contact.
template(opts)(opts: TemplateOptions)Template message.
event(opts)(opts: EventOptions)Event message (name, startAt, optional endAt/location/call/canceled).
groupInvite(opts)(opts: GroupInviteOptions)Group-invite card (jid, code, optional subject/caption/expiresAt/thumbnail).
product(opts)(opts: ProductOptions)Business product card (image, title, businessOwnerId, optional price/currency/productId/etc.).
requestPhoneNumber()()Ask the recipient to share their phone number.
sharePhoneNumber()()Share your own phone number.
limitSharing(enabled?)(enabled?: boolean)Toggle advanced chat-privacy (limit sharing); defaults true.
album(items)(items: AlbumItem[])Media album.
reply(quoted)(quoted: WAMessage | WAMessageKey)Quote a message.
mentions(jids)(jids: string[])Mention specific JIDs.
mentionAll()()Mention all group members.
disappearing(seconds)(seconds: number)Set disappearing timer.
then(...)thenableAwaiting the builder sends the message and resolves to a WAMessageKey.
sendMessage(...)low-level sendInternal/escape-hatch send.

EditBuilder

MethodSignatureDescription
text(content)(content: string): thisReplace text.
image(src, opts?)(src: MediaSource, opts?: ImageOptions): thisReplace with image.
video(src, opts?)(src: MediaSource, opts?: VideoOptions): thisReplace with video.

Builder mutations & helpers

ExportKindDescription
deleteMessage(...)functionDelete a message. Options: DeleteOptions.
reactToMessage(...)functionReact to a message.
forwardMessage(...)functionForward a message.
isJid(value)function(value: string): boolean — JID-format check.
resolveUsername(...)functionResolve a username to a JID. Socket: UsernameResolveSocketLike.
BuilderSocketLike / TextOptionstypeBuilder socket shape + text options.

Builder types

BuilderState, BuilderContext, MediaSource, ImageOptions, VideoOptions, VideoNoteOptions, AudioOptions, DocumentOptions, StickerOptions, AlbumItem, ListOptions, ListSection, PollOptions, LocationOptions, TemplateOptions, EventOptions, GroupInviteOptions, ProductOptions, ButtonDef, InteractiveButton (ReplyButton, UrlButton, CopyButton, CallButton, ReminderButton, CancelReminderButton, LocationRequestButton, AddressButton), BottomSheetOptions, LimitedTimeOfferOptions.

Events

Inbound event payloads and helpers. See Events.

client.on('message', (ctx) => console.log(ctx.chatType, ctx.text, ctx.senderId)) client.on('text', (ctx) => console.log(ctx.text, ctx.senderId)) client.on('call-incoming', (call) => console.log(call))

The message event is an umbrella that fires once for any inbound message regardless of type, delivering the same MessageContext as the typed events (text, image, …). Use it as a single catch-all entry point.

MessageContext notes:

  • uniqueId — 16-char uppercase hex, stable per message (remoteJid|id|fromMe).
  • staticId — 16-char uppercase hex, stable per room + sender (same value for every message from one sender in one room).
  • mentions — resolved to PN (LID mentions mapped back to phone-number JIDs).
  • senderDevice — detected (android | ios | web | desktop | unknown).
  • Content-derived flags: isEdited, isDeleted, isPinned, isUnPinned, isBot, isStatusMention, isGroupStatusMention, isStory, isHideTags.
  • chatType values include album, group-invite, product, order, payment (plus text/image/video/audio/document/sticker/poll/contact/location/live-location/event/buttons/list/interactive/template/unknown).
ExportKindDescription
buildMessageContext(...)functionBuild the rich MessageContext from a raw message.
dropSpoofedSelfOnly(upsert)functionGuard that drops spoofed self-only protocol messages.
SELF_ONLY_PROTOCOL_TYPESconstFrozen list of self-only protocol types.
MessageContexttypeThe rich, lazy message object passed to handlers.
ChatType / SenderInfo / SenderDevicetypeSender/chat metadata.
Payload typestypeButtonClickPayload, CallPayload/CallBase, DeletePayload, EditPayload, GroupJoinPayload, GroupLeavePayload, GroupUpdatePayload, GroupParticipantInfo, HistorySyncPayload, LimitedPayload, ListSelectPayload, MemberTagPayload, NewsletterPayload, PollVotePayload, PresencePayload, ReactionPayload, QuotedRef.
Media contexttypeContextMedia, MediaDescriptor, MediaDownloadResult, MediaKind.
ctx.media variantsinterfaceMediaAttachment, PollMedia, ContactMedia, LocationMedia, EventMedia, AlbumMedia, GroupInviteMedia, ProductMedia, OrderMedia, PaymentMedia, LinkPreviewMedia, ButtonsMedia, ListMedia, InteractiveMedia, TemplateMedia (see below).
MentionstypeMentionContext, MentionAllContext.
Event mapstypeInboundEventMap, InboundEventName.
CitationstypeCitationConfig, CitationPredicates.
MisctypeBuildContextInput, UpsertPayload, SelfOnlyProtocolType.

ctx.media variants

ctx.media is a discriminated union keyed on type. New variants added in v4.4 (all fields nullable unless noted):

Variant (type)Fields
albumexpectedImageCount, expectedVideoCount.
group-invitegroupId, groupName, inviteCode, caption, expiresAt.
productproductId, title, description, price, currency, retailerId, url, businessOwnerId.
orderorderId, title, itemCount, total, currency, status, message.
paymentkind ('request' | 'send' | 'invite'), amount, currency, note, expiresAt.
linkurl, title, description.

Commands

Prefix-based command routing. See Commands.

client.command('ping', async (ctx) => ctx.reply('pong')) client.use(async (ctx, next) => { console.log(ctx.command); await next() })
ExportKindDescription
parseCommand(text, prefixes)functionParse text into ParsedArgs.
CommandRegistryclassHolds command definitions: register, resolve, list.
runMiddleware(...)functionRun a middleware chain.
attachCommandDispatcher(...)functionWire the dispatcher to a client.
CommandContextinterfaceExtends MessageContext with command, args, flags, json, reply, react, edit.
CommandHandler / MiddlewaretypeHandler and middleware function shapes.
CommandDefinition / ParsedArgs / CommandPrefixtypeDefinition, parsed args, and prefix types.
DispatcherDeps / DispatcherHandle / ResolvedCommandtypeDispatcher internals.

Automation

Rate limiting, queues, broadcast, scheduling, presence. See Broadcast & Schedule.

ExportKindDescription
RateLimiterclassToken-bucket limiter. Method: acquire(jid?). Options: RateLimiterOptions, RateLimiterClock.
TaskQueueclassConcurrency-limited queue. Methods: add(task), onIdle(). Options: TaskQueueOptions, TaskQueueClock.
runBroadcast(...)functionFan-out send. Options: BroadcastOptions, BroadcastResult, BroadcastDeps.
SchedulerclassPersistent scheduler. Methods: scheduleAt(...), loadPending(), dispose(). Deps/types: SchedulerDeps, SchedulerTimer, ScheduleHandle, ScheduledContentSnapshot.
PresenceModuleclassMethods: online(), offline(), typing(jid, ms?), recording(jid, ms?). Types: AutomationSocketLike, WAPresence. Full guide: Presence.
RetryPolicy / ScheduledJob / ScheduledJobRecordtypeRetry config and scheduled-job shapes.

Domain Modules

Accessed via client.group, client.privacy, client.newsletter, client.community, client.profile, client.chat, client.contact, client.business. Full guides: Groups · Communities · Newsletters · Privacy & Blocking. See also Client & Lifecycle.

const meta = await client.group.metadata('xxx@g.us') await client.group.addMember('xxx@g.us', ['628xxx@s.whatsapp.net'])

GroupModule

create, addMember, removeMember, promote, demote, updateSubject, updateDescription, leave, metadata, tagMember, inviteCode, revokeInvite, acceptInvite, toggleEphemeral, setting, list, inviteInfo, joinRequests, approveJoin, rejectJoin, joinApproval, memberAddMode.

PrivacyModule

set, get, block, unblock, blocklist, disappearingMode.

NewsletterModule

create, follow, unfollow, metadata, updateName, updateDescription, updatePicture, mute, unmute, delete, removePicture, react, unreact, subscribers, messages, adminCount, changeOwner, demote.

CommunityModule

create, createGroup, linkGroup, unlinkGroup, subGroups, leave, updateSubject, updateDescription, inviteCode, revokeInvite, acceptInvite, metadata, list, inviteInfo, toggleEphemeral, setting, memberAddMode, joinApproval.

ProfileModule

setName, setStatus, setPicture, removePicture, getPicture, getStatus.

ChatModule

archive, unarchive, pin, unpin, mute, unmute, markRead, markUnread, star, unstar, delete, clear.

ContactModule

check, exists, save, remove. Type: ContactCheckResult.

BusinessModule

profile, catalog, collections, orderDetails, createProduct, updateProduct, deleteProduct.

Domain types: ParticipantUpdateResult, PrivacyConfig, PrivacySettings, LinkedGroup, DomainSocketLike.

Media

FFmpeg/sharp-backed media processing. See Media.

import { Media } from 'zaileys' const m = new Media('./input.mp3') const opus = await m.audio.toOpus() const thumb = await m.video.thumbnail()
ExportKindDescription
MediaclassFacade with getters: audio (toOpus/toMp3/convert/waveform), video (toMp4/thumbnail), image (toJpeg/thumbnail/resize), sticker.create, document.create, thumbnail.get.
AudioProcessor / VideoProcessor / ImageProcessor / StickerProcessor / DocumentProcessorclassLow-level processors.
FFmpegProcessor / FileManager / BufferConverter / MimeValidatorclassFFmpeg/IO helpers.
initializeFFmpeg(disable?) / detectFileType(buffer) / generateId() / ffmpegTransform(...)functionSetup and transform helpers.
FFMPEG_CONSTANTSconstShared MIME/extension constants.
MediaInput / FileExtension / AudioType / StickerShapeTypetypeInput and format types.
FFmpegConfig / StickerMetadataTypeinterfaceConfig and sticker metadata.

Connection

Lower-level connection primitives (advanced). See Client & Lifecycle.

ExportKindDescription
createPairingFlow(opts)functionBuild a pairing-code flow. Types: PairingFlow, PairingFlowOptions, PairingFlowResult.
createReconnectStrategy(...)functionReconnect backoff strategy. Types: ReconnectStrategy, ReconnectDecision, ReconnectStrategyDeps.
createConnectionStateMachine(initial?)functionState machine. Types: ConnectionStateMachine, StateTransitionListener.
signalKeyStoreFromAuthStore(store, logger?)functionAdapt an AuthStore into a Baileys signal key store.
renderQrInTerminal(qrString)functionRender a QR string in the terminal.
mapDisconnectReason(code) / isFatalDisconnect(r) / shouldClearAuth(r) / shouldReconnect(r)functionDisconnect-reason classifiers. Type: DisconnectReasonDomain.
normalizePhoneNumber(raw) / validateE164(raw)functionPhone-number helpers.

Utilities

ExportKindDescription
createLogger(options?)functionBuild a Pino-based logger. Options: CreateLoggerOptions.
adoptLogger(maybe, fallback?)functionNormalize a partial logger into a full Logger.
chunk(arr, size)functionSplit an array into fixed-size chunks.
isJid(value) / isLidJid(jid) / isPnJid(jid)functionJID predicates: any WhatsApp JID / @lid / phone (@s.whatsapp.net,@c.us).
normalizeJid(jid)functionStrip device suffix and canonicalize a JID (null for invalid).
jidToPhone(jid) / phoneToJid(phone)functionConvert a phone JID to digits / build a user JID from a phone.
jidDecode(jid) / jidEncode(user, server, device?)functionDecode a JID to { user, server, device? } / build a JID from parts (re-exported from Baileys).
jidNormalizedUser(jid) / areJidsSameUser(a, b)functionNormalized user JID (strips device) / same-user check ignoring device/LID.
isJidGroup(jid) / isJidBroadcast(jid) / isJidNewsletter(jid)functionJID predicates: group (@g.us) / broadcast / newsletter (@newsletter).
isLidUser(jid) / isPnUser(jid)function@lid user / phone-number user (@s.whatsapp.net) predicates.
getDevice(jid)functionDevice kind decoded from a JID (re-exported from Baileys).
computeUniqueId(key) / computeStaticId(roomId, senderId)function16-char UPPERCASE hex hashers — the context’s uniqueId / staticId.
extractLinks(text)functionExtract http(s) URLs from a string.
senderDeviceOf(jid)functionDecode device from a JID: 'android' | 'ios' | 'web' | 'desktop' | 'unknown'.
epochSecondsToMs(value)functionEpoch seconds → ms; accepts number | string | bigint | Long.
loadMedia(src, opts?) / detectMimeFromBuffer(buffer)functionResolve a media source to { buffer, mime, size } / sniff a buffer’s MIME. Types: LoadedMedia, LoadMediaOptions.
ZaileysLogger / LoggerLeveltypeLogger instance and level types.

See Utilities for full signatures and examples.

Errors

Typed error classes per subsystem. Each carries a discriminated code. See Error Handling for handling patterns.

import { ZaileysBuilderError } from 'zaileys' try { await client.send(jid).text('hi') } catch (e) { if (e instanceof ZaileysBuilderError) console.error(e.code, e.message) }
ExportKindDescription
ZaileysBuilderErrorclassBuilder/send failures. Code: BuilderErrorCode.
ZaileysDomainErrorclassGroup/privacy/newsletter/community failures. Code: DomainErrorCode.
ZaileysCommandErrorclassCommand parsing/dispatch failures. Code: CommandErrorCode.
ZaileysAutomationErrorclassBroadcast/schedule/queue failures. Code: AutomationErrorCode.
ZaileysStoreErrorclassStore failures. Code: StoreErrorCode.

Misc Types

ExportKindDescription
LIDMappinginterfaceLinked-device ID mapping.
LIDMappingUpdatePayloadtypePayload for LID mapping updates.
⚠️

Optional native dependencies (SQLite, Postgres pg, Redis, Convex, FFmpeg, sharp) are loaded lazily. Install only the adapter you use — see Storage Adapters and Media.

Last updated on