Skip to main content
Version: v0.31.0

Sessions & multi-session

Drive a WhatsApp account from OpenWA by running it as a session: a linked WhatsApp number with its own connection, chats, and message history. This guide takes a session through its full lifecycle — create, start, link, monitor, stop, delete — and shows how to run many sessions on one instance and address each one by id.

Prerequisites
  • A running OpenWA instance reachable at http://localhost:2785/api (see Installation).
  • An API key with the operator role for write actions (create, start, stop, delete) and for linking — fetching the QR (GET /qr) and requesting a pairing code both require an operator key too. Plain read routes (list/get a session, stats) accept any valid key, but of these a key restricted to chats (v0.23.6+) can only get a single session. See Authentication.
  • A phone with WhatsApp installed, to scan the QR or enter a pairing code.

All examples use the local base URL http://localhost:2785/api and send the key in the X-API-Key header. In production, swap in your own domain over TLS — the /api prefix is unchanged. Replace YOUR_API_KEY with a real key; see Authentication for how to obtain one.

The session lifecycle​

A session moves through a fixed set of states. The status field is always lowercase on the wire.

StatusMeaning
createdThe session record exists, but the WhatsApp engine has not started.
initializingThe engine is booting and opening the WhatsApp connection — or, on the Baileys engine, waiting out reconnect backoff after a transient drop.
qr_readyA QR code (or pairing code) is available to scan or enter.
authenticatingThe link was accepted; the session is finishing the handshake. On Baileys this lasts seconds and cannot stall: WhatsApp asks for a restart as soon as it accepts the link, so the session passes back through initializing before ready (since v0.23.3).
readyConnected. The session can send and receive messages.
action_requiredConnected, but the engine needs a human action before the session is fully usable — for example a whatsapp-web.js "What's new on WhatsApp Web" onboarding modal that auto-dismissal could not clear. lastError carries a readable reason (since v0.12.0).
disconnectedStopped on purpose, or the connection dropped. Can be started again.
failedThe engine hit an error it does not retry (a startup or authentication failure, a Baileys 440 or 403 close), or the reconnect budget ran out. lastError carries the reason. Can be started again; see the warning below the diagram.
Start a failed session instead of deleting it

A failed session is not retried automatically, and a gateway restart leaves it failed with lastError null, because the process holds that reason in memory. POST /api/sessions/:id/start boots a fresh engine for it, because a start does not look at the session's status. While lastError is set, read it, remove the cause, then start the session. A start does not delete the stored credentials; a delete does.

The credentials are still on disk after the failures that leave the link intact: on Baileys a 440 close (another instance holds the account) or a 403 close (WhatsApp rejected the account), and on whatsapp-web.js a restored session that never became ready. A start reuses them, so once the cause is gone the session reconnects without a new QR scan.

Delete and recreate only to discard the session, for example to bind it to a different WhatsApp number or to pair from scratch, as some lastError texts suggest. That removes the message history, webhooks, templates and the other records stored for the session along with its credentials, and the recreated session needs a new QR scan (see Stop or delete a session).

The status values are the same regardless of the WhatsApp engine in use (Baileys or whatsapp-web.js); the engine is selected per instance, not per session.

Auto-reconnect and shutdown drain

When auto-reconnect is off (budget 0), a drop that the gateway's own reconnect handles (see Auto-reconnect mechanics for which drops those are) settles the session in failed carrying the reason Auto-reconnect is disabled (max attempts set to 0); the session was left disconnected — restart it manually. The reason no longer reports a misleading "reconnection failed after 0 attempts", but the status is the same terminal failed an exhausted finite budget produces, so branch on lastError rather than on the status to tell the two apart. A disconnect during a graceful shutdown drain (SIGTERM/SIGINT) is left at disconnected rather than scheduling a reconnect that would race the teardown; a later start or auto-restore re-initializes it cleanly.

Since v0.25.0 a session start that crosses the shutdown boundary answers 503 and is left for the next boot rather than marked failed. New requests during teardown answer 503 with Connection: close, apart from health probes under /api/health, dashboard HTML and CORS preflights. /api/infra/health is not exempt. Stop taking work when readiness fails and allow the deployment's 75-second termination grace period to drain it.

Auto-reconnect mechanics​

Two layers reconnect a dropped session, and the per-session reconnect settings govern only one of them:

  • The gateway's own reconnect handles every drop on whatsapp-web.js. On Baileys it handles only a close in which WhatsApp logged the device out; the engine wipes the dead credentials first, so that reconnect comes back at qr_ready with a fresh QR. maxReconnectAttempts and reconnectBaseDelay apply to this layer, as described below.
  • The Baileys engine's internal retry handles every other Baileys close that is not terminal. It waits 1 second, doubling to a 60-second cap plus up to 1 second of jitter, with no attempt cap, and its counter restarts when a QR is scanned or a pairing code is accepted, when an unscanned QR window runs out, and when a close comes more than 5 minutes after the previous one. Opening a connection does not reset it (since v0.24.0), so a link that drops again within 5 minutes of its previous close keeps climbing the backoff. The two settings do not reach it, so maxReconnectAttempts: 0 does not stop a Baileys session from retrying a network drop; stop the session to end it.

By default the gateway's reconnect retries without a limit: exponential backoff starting at 5 seconds, capped at 5 minutes, with the attempt counter reset only once the session has stayed ready for 5 minutes (since v0.24.0; before that, reaching ready reset it). A session that drops sooner keeps its streak, so with a finite maxReconnectAttempts one that keeps dropping within 5 minutes of ready spends its budget and ends failed. Before v0.23.5 the delay parked at a 1-hour cap and the counter also reset after 5 stable minutes; that reset was keyed on when the last attempt was scheduled, so once the backoff delay itself outgrew the window it fired on every further attempt, and a high maxReconnectAttempts was never exhausted. config.maxReconnectAttempts opts out — 0 turns this reconnect off, and 1–20 caps the attempts. Since v0.24.0 POST /api/sessions refuses an out-of-range or mistyped config value with 400, as PATCH /config does, so the clamp into 0-20 now applies only to a value already stored: there a negative value becomes 0 and turns this reconnect off rather than capping it at one attempt. A session that exhausts a finite budget lands in failed, and its dead engine is evicted from the registry — the same teardown the terminal-error path uses — so it frees its concurrency slot and the next start() boots clean instead of being rejected as already started.

Both reconnect settings, and auto-reject, can be changed on a session that is already linked — see Read and change a session's config.

A watchdog probes every ready engine every 60 seconds; two consecutive probe failures count as a disconnect, so a silently dead engine re-enters the reconnect pipeline within about 2 minutes. On the Baileys engine, a transient socket close also reports initializing for the whole reconnect backoff and restores ready on the next open, so liveness probes and sends fail fast instead of passing against a dead socket (previously the session kept reporting ready for up to the 60-second backoff cap). Every 5th consecutive attempt, on either layer, emits a session.reconnect_loop webhook event, a warning log, and a Prometheus counter tick (openwa_session_reconnect_loop_alerts_total) — wire one of those into your monitoring so a looping session does not go unnoticed. The Baileys engine's internal retry has raised these since v0.23.5; before that, a Baileys session retrying a network drop emitted none of them.

On the Baileys engine, two close codes are terminal and never retried: 440 (connectionReplaced — another live instance holds the account) and 403 (forbidden — the account is banned or blocked).

1. Create a session​

POST /api/sessions registers a new session. The only required field is a unique name: 3–50 characters, letters, numbers, and hyphens only. A new session starts in created and is not connected yet.

curl -X POST "http://localhost:2785/api/sessions" \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "name": "my-bot" }'

Response 201 Created. It is the same projection every read route returns, not the raw entity: config, proxyUrl and proxyType are stripped here too, and the internal lastActiveAt is exposed as lastActive.

{
"id": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",
"name": "my-bot",
"status": "created",
"phone": null,
"pushName": null,
"connectedAt": null,
"lastActive": null,
"createdAt": "2026-06-25T09:00:00.000Z",
"updatedAt": "2026-06-25T09:00:00.000Z",
"lastError": null,
"restriction": null,
"engineLoaded": false
}

Save the id. Every later call for this session uses it in the path.

Duplicate names conflict

Creating a session with a name that already exists returns 409 Conflict. A name that breaks the format rule, a config object over 16,384 serialized bytes (v0.28.0+), or any extra, undeclared body field returns 400 Bad Request.

On SQLite, since v0.26.0, a create that finds another database transaction still open after 10 seconds answers 503 and stores nothing, so send it again.

To route a session's WhatsApp traffic through a proxy, pass proxyUrl at create time. Its scheme (http, https, socks4, or socks5) selects the protocol; proxyType is deprecated, ignored, and accepted only for compatibility:

{ "name": "my-bot", "proxyUrl": "http://proxy.example.com:8080" }

Since v0.24.0, setting proxyUrl at create time needs an admin key. An operator key without session scope answers 403 Setting proxyUrl requires an ADMIN key.

On the whatsapp-web.js engine, authenticated HTTP/HTTPS proxies work — pass the credentials in the proxyUrl and the engine hands them to Chromium's proxyAuthentication (a plain --proxy-server ignores credentials). Since v0.29.0, when a session uses a credentialed http or https proxy, the gateway also intercepts https://web.whatsapp.com/sw.js and serves a pass-through service worker so Chromium's unauthenticated service-worker script fetch cannot fail with 407 before page.authenticate runs. SOCKS proxies that require a username/password are not supported on this engine: Chromium cannot authenticate a SOCKS proxy at all, so OpenWA logs a warning instead of failing with an opaque navigation timeout, and since v0.28.0 a start failure or disconnect during launch on a credentialed SOCKS proxy appends a note to lastError explaining that limitation. IP-authorized proxies (no credentials) work over every proxy type.

On the Baileys engine, proxyUrl (http, https, socks4, or socks5, credentialed form included) is applied through a Node-layer agent on the WhatsApp WebSocket and on media uploads (since v0.11.1). Since v0.23.5 an http, https or socks5 proxy also carries what the engine fetches over HTTP: inbound media downloads, the WhatsApp Web version lookup, the history-sync and app-state payloads of the initial sync, and a product card's image URL. Since v0.23.6 a socks4 proxy carries them too. On v0.23.5 it could not, because the HTTP client had no SOCKS4 transport: inbound media was skipped and arrived as the omitted marker, the version lookup fell back to the disk cache or the bundled default, and the initial-sync payloads and the product image went direct. Credentials authenticate on the socket itself, so the Chromium first-CONNECT 407 limitation that can bite the whatsapp-web.js proxy-auth path does not apply here. The exception is socks4, which has no authentication step: the user name travels as the connect request's user id and the password is dropped, and since v0.23.6 a warning at session start says so. Use socks5, http or https for a proxy that needs a password. Since v0.23.6 the Baileys wire log (BAILEYS_LOG_LEVEL, silent by default) redacts credential fields such as the proxy password. Earlier releases wrote the whole proxy configuration of a failed SOCKS connect to stdout, password included, when that log was turned on (at debug, for example); if you kept such logs, rotate the proxy password. A socks4 or socks5 proxy at an IPv6 literal, such as socks5://[2001:db8::1]:1080, connects since v0.23.6; earlier releases sent the brackets on the wire as part of the hostname. An unusable proxy value fails the session start instead of silently falling back to a direct connection.

Since v0.23.6 a URL you hand the gateway to fetch for a session leaves through that session's proxy as well, on both engines: the media url of a send, status or picture route, the url of POST /api/sessions/:id/media/convert/voice and .../convert/video, and, on Baileys, the link preview of a text send (including customLinkPreview.thumbnailUrl in v0.27.0+). Before, these fetches left from the gateway's own address. The proxy used is the one the session's running engine started with, or the stored one when the session is not running. Set SESSION_PROXY_URL_FETCH=false (see Configuration) when the proxy only routes to WhatsApp and cannot reach arbitrary media hosts; those fetches then go direct again. A media fetch through the proxy that fails or times out before any response arrives answers 503, whether the proxy or the target behind it is at fault, since the gateway cannot tell the two apart; the same failure on a direct fetch answers 400. The SSRF guard checks the URL either way, but only a direct fetch or a SOCKS proxy keeps its DNS-rebind pinning: an http or https proxy resolves the destination name itself, so a name that passes the check and then re-resolves to an internal address reaches it, if the proxy can.

Read or change the proxy afterwards (v0.23.4+)​

Every session route strips proxyUrl and proxyType from its response, the create route included, so before v0.23.4 a proxy set at create time could be neither read back nor changed. Two routes now cover it.

curl http://localhost:2785/api/sessions/SESSION_ID/proxy \
-H "X-API-Key: YOUR_API_KEY"
{
"enabled": true,
"proxyType": "socks5",
"proxyHost": "proxy.example.com:1080",
"hasCredentials": true
}

The URL itself never comes back. proxyHost is the host:port, and hasCredentials only reports whether a username or password is stored, never what it is. With no proxy configured, enabled is false and both proxyType and proxyHost are null.

PATCH takes the URL on its own and derives proxyType from the scheme, so there is no separate type field to keep in step. Send null to clear it:

curl -X PATCH http://localhost:2785/api/sessions/SESSION_ID/proxy \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "proxyUrl": "socks5://user:pass@proxy.example.com:1080" }'

Anything that is not an http, https, socks4 or socks5 URL, or is longer than 255 characters, answers 400; an unknown session answers 404. Since v0.23.6 this route and POST /api/sessions also answer 400 (proxyUrl credentials contain an invalid percent-escape; write a literal % as %25) when the credentials hold a % that does not begin a valid percent-escape. Before, such a URL was stored and then failed every start with an opaque URI malformed. A URL stored by an earlier release is not re-checked after an upgrade, either at boot or at start: if a session still fails to start with URI malformed, set its proxy again through this route (or clear it with null), writing each literal % in the credentials as %25, then start the session.

Nothing restarts. Each engine reads the proxy as it launches, so a change takes effect on the session's next start, the same rule as the reconnect settings on PATCH /config. Stop and start the session to apply it now. The URL fetches described above follow the same rule: a running session keeps fetching through the proxy it started with.

Since v0.24.0 PATCH needs an admin key that is not session-scoped; setting proxyUrl when creating a session also requires admin. A scoped key answers 403 Session-scoped API keys are not permitted on this route, and the refusal is written to the audit log. Sending a session's whole egress through a host of your choosing is an instance-level decision rather than a per-session one, and POST /sessions was already closed to scoped keys the same way, so this route hands a caller no reach it did not already have. GET carries no such fence; like the config read, it refuses a key restricted to chats with 403 API key is restricted to selected chats (v0.23.6+).

2. Start the session​

Creating a session does not connect it. Call POST /api/sessions/:id/start to boot the engine:

curl -X POST "http://localhost:2785/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/start" \
-H "X-API-Key: YOUR_API_KEY"

Response 200 — the status moves to initializing, then to qr_ready once a code is available:

{
"id": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",
"name": "my-bot",
"status": "initializing",
"phone": null,
"pushName": null,
"connectedAt": null,
"lastActive": null,
"createdAt": "2026-06-25T09:00:00.000Z",
"updatedAt": "2026-06-25T09:05:00.000Z",
"lastError": null,
"restriction": null,
"engineLoaded": true
}

A start that cannot go ahead answers an error instead:

StatusMeaning
400The session is already running or already starting, or this node is at its MAX_CONCURRENT_SESSIONS cap (Maximum concurrent sessions reached (N))
404Session not found
409A name-keyed credential teardown is still in flight (the body carries code: 'SESSION_NAME_TEARDOWN_PENDING'; retry shortly), or another node holds the session's engine. With no code: a stop, a logout (since v0.26.0) or force-kill that found an engine to kill, or a data import of this session began or finished while the start was waiting, or a delete of it was still running or began removing the session while the start waited. After a stop, logout or force-kill, send the start again; after a delete that completed, the retry answers 404, and after one that failed part-way a new start clears its stop and starts what remains
503The gateway is shutting down (see the shutdown paragraph above), the database could not check or claim session ownership (v0.28.0+), or the engine's browser or socket died during launch and the one automatic retry failed too. No engine is left running, so retry
504The engine did not finish starting within its timeout. The engine is torn down, so retry. On whatsapp-web.js an unreachable proxyUrl and the authentication timeout are two more causes. Since v0.31.0 that timeout (WWEBJS_AUTH_TIMEOUT_MS, 30 seconds by default) bounds the wait for the page's connection to WhatsApp, which had no limit of its own before, as well as the page's boot, and a start that runs out of it leaves the session failed

Link the WhatsApp account in one of two ways. Both require the session to be in qr_ready. Use a QR code for a quick manual link, or a pairing code when you cannot show a QR.

Option A — QR code​

Fetch the QR as a PNG data URL with GET /api/sessions/:id/qr, render it, and scan it from your phone under WhatsApp → Linked Devices → Link a device:

curl "http://localhost:2785/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/qr" \
-H "X-API-Key: YOUR_API_KEY"

Response 200:

{
"qrCode": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
"status": "qr_ready"
}

Drop qrCode straight into an <img src="…"> to display it. If the session has not reached qr_ready yet (or is already authenticated), the route returns 400 Bad Request — start the session first, then retry. On the Baileys engine, after a pairing code is requested, the engine waits five minutes from the latest request for the code to be entered before registering again with a new QR, and from 60 seconds after the request until that new QR arrives this route also answers 400 because no QR is ready yet (v0.27.0+). A stale QR is no longer emitted while a whatsapp-web.js session is tearing down, so a buffered QR event can no longer flip a disconnecting session back to qr_ready. Since v0.23.3 both engines also drop the cached code the moment their socket or page dies, so during a reconnect this route answers its 400 instead of handing back a QR that can no longer be scanned. The Dashboard renders the QR for you on its Sessions page.

Option B — pairing code​

Request an 8-character pairing code tied to a phone number, then enter it on the phone under Linked Devices → Link with phone number. The number must be digits only in international format (country code + number, no +, spaces, or dashes), 6–15 digits:

curl -X POST "http://localhost:2785/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/pairing-code" \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "phoneNumber": "628123456789" }'

Response 201:

{ "pairingCode": "ABCD1234", "status": "qr_ready" }

Requesting a code before the session reaches qr_ready answers 409 Conflict: the engine is still connecting, or reconnecting after a drop, so the request never reached WhatsApp. Wait for qr_ready and retry. On the Baileys engine a socket that has already begun closing refuses the request while status still reads qr_ready, for up to the WebSocket close timeout (30 s), so retry once before treating that 409 as a bad state (since v0.23.3). On whatsapp-web.js the same status also refuses a number that is the stored phone of another session (since v0.26.0); see the warning below.

On the whatsapp-web.js engine, WhatsApp Web reloads its QR page roughly every 20 seconds while the session is unlinked, so the gateway retries a request that lands mid-reload, up to four attempts. When all of them fail, the route answers 503 since v0.23.6 (it answered 500 before): the condition is transient, so retry. The Baileys engine has no page to reload and does not answer this 503.

On whatsapp-web.js, a pairing code can unlink an existing device

Request a code only for a number you are prepared to re-link. A pairing request for a number that already has a linked session on this gateway has been observed to end with WhatsApp unlinking that device within about a minute: the session disconnects with reason LOGOUT, loses its stored credentials, and returns to qr_ready with no phone. Before v0.26.0 nothing refused such a request. Since v0.26.0 a number that is the stored phone of another session of this gateway answers 409 and WhatsApp is not asked (the Brazilian, Mexican and Argentine mobile spellings of one number count as the same, and a session's own number is not refused): delete that session, or log it out while it runs, first. The gateway cannot see a link made on another gateway or only on the phone, so a request for such a number can still unlink that device. A retry after a 503 carries the same risk. The Baileys engine was not affected in the same tests and accepts the request, since its sessions are companion devices that may share a number. If a session of that number must stay up, link the new one by QR.

On Baileys, if the phone answers "Couldn't link device" after the code is entered while linking the same account by QR works, check BAILEYS_BROWSER_NAME first. Since v0.25.0 the default is Ubuntu, a standard OS name; before that it was OpenWA. On an older gateway, or with the variable set to a custom name, set it to a standard OS name such as Ubuntu (see Configuration), restart OpenWA itself, and request a fresh code. The name is read when OpenWA boots, so stopping and starting the session is not enough.

After the link is accepted, the session transitions through authenticating to ready, and answers the same 409 to a second request until it gets there. On Baileys it passes back through initializing on the way, because WhatsApp asks for a restart as soon as it accepts the link. Poll the session (next step) to confirm.

4. Confirm the session is ready​

Read a single session with GET /api/sessions/:id:

curl "http://localhost:2785/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a" \
-H "X-API-Key: YOUR_API_KEY"

Response 200 — once status is ready, the linked phone and pushName are populated and the session can send and receive:

{
"id": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",
"name": "my-bot",
"status": "ready",
"phone": "628123456789",
"pushName": "My Bot",
"connectedAt": "2026-06-25T08:14:02.000Z",
"lastActive": "2026-06-25T09:01:55.000Z",
"createdAt": "2026-06-20T11:30:00.000Z",
"updatedAt": "2026-06-25T09:01:55.000Z",
"lastError": null,
"restriction": null,
"engineLoaded": true
}

lastError is non-null when status is failed or action_required (where it carries the human-readable reason until the gateway restarts), and on an initializing session in two cases: from the fifth consecutive attempt of an engine retrying a dropped connection on its own, until the session is ready or a QR arrives (a QR window that runs out unscanned is not an attempt; on Baileys since v0.30.0 lastError ends with a sentence naming the stage where the last connection closed, such as The last connection closed after WhatsApp confirmed the login, before the session opened. or The last connection closed before WhatsApp confirmed the login.), and while a reconnect waits to retry after the engine failed to relaunch. Any other status clears it, so branch on status rather than on a non-null lastError to tell a terminal failure from a reconnect in progress. restriction is non-null only when WhatsApp itself has placed a limit on the account (or on Baileys since v0.30.0 when WhatsApp asked for a passkey during linking) — see Account restrictions below. engineLoaded reports whether the gateway actually holds a live engine for this session: one in the answering process or, on a multi-node deployment since v0.23.7, a live claim by the node that runs it. status: disconnected alone cannot say whether a start is the right call (a stopped session has no engine; a session mid-reconnect backoff still has one registered and answers start with 400). With engineLoaded: false, start is the route that acts and logout and force-kill answer 400, while stop still answers 200 and records the stop, so the session stays down across a restart until the next start. Read routes strip config, proxyUrl, and proxyType, and rename the internal lastActiveAt field to lastActive (updated at most once every 30 seconds per session during live traffic since v0.28.0). engineLoaded is a live field added in v0.12.1 — a gateway older than that omits it.

Watch status changes instead of polling

Rather than polling on a loop, subscribe to live session.status, session.qr, session.authenticated, and session.disconnected events through Webhooks, or read the same events from the WebSocket channel when your client can hold an outbound connection instead of exposing an inbound endpoint. The status values in those events match the lowercase enum above. Since v0.23.5 the WebSocket session.qr event reaches only operator and admin keys, matching the role GET /api/sessions/:id/qr already required: a viewer key still subscribes without error, by name or through a wildcard, and simply never receives the pairing QR. Webhook delivery of the same event is not role-gated.

Once the session is ready, send your first message — see Sending Messages.

LID-addressed contacts resolve transparently

WhatsApp has begun addressing some individual chats by privacy id (@lid) instead of the phone-number WID (@c.us). A send to an @lid recipient works without extra handling: an @lid id is used as given, and a @c.us number is delivered to the contact's @lid when the engine finds one, across text, media, location, contact, and sticker messages. On whatsapp-web.js a lookup that fails falls back to the original id, and if the page then cannot address the contact the send answers 400. Since v0.25.0 Baileys checks a phone recipient without a known LID before sending: an unregistered number returns 400, and a lookup that gets no answer returns 503 with nothing sent (see Common errors). You do not need to detect or rewrite @lid addresses yourself.

5. Stop or delete a session​

Stop to disconnect WhatsApp but keep the session record, so you can start it again later without re-linking:

curl -X POST "http://localhost:2785/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/stop" \
-H "X-API-Key: YOUR_API_KEY"

The status becomes disconnected. Since v0.23.6 the session.status event announcing it goes out only after the engine is released, for a stop, a logout and a force-kill alike, so a consumer that reads the session on that event already sees engineLoaded: false. Before, it could arrive while the engine was still tearing down, which on whatsapp-web.js lasted as long as Chromium took to close. Since v0.19.0, a stop whose graceful disconnect fails escalates to a force-destroy instead of hanging — a wedged browser no longer leaks until the next start. Only when both the graceful disconnect and the forced teardown fail does the route answer a retryable 502 (code: 'SESSION_STOP_INCOMPLETE', session left disconnected, no success audit entry). That stop has already released the engine, so restart the node to reap a leaked process; force-kill needs a live engine and answers 400. To force a session down directly, use POST /api/sessions/:id/force-kill, which SIGKILLs the stuck engine and tears it down. Since v0.24.0 a force-kill whose teardown does not complete answers 502 with code: 'SESSION_FORCE_KILL_INCOMPLETE' (session left disconnected, no success audit entry); restart the node to reap the leaked process. A session that fails terminally or cannot re-initialize no longer strands its browser process or wedges at "already started" — the dead or half-built engine is evicted from the session registry and its Chromium is force-killed automatically, freeing the concurrency slot for a clean restart. Since v0.12.0, force-killing a session with no live engine returns 400 instead of 200 — read it as "there was nothing to kill". To reconcile a stale row, call POST /api/sessions/:id/stop instead, which answers 200 for a session with no engine and records the stop.

A stop answers a retryable 503 when the database does not answer the check of whether another node holds the session (v0.28.0+) and, since v0.31.0, when it does not answer the read of the session, the write that records the stop or the check that record makes after a missed write. A force-kill answers it, since v0.31.0, when the database does not answer the read of the session. Nothing was stopped or killed in any of these cases, and a stop whose record the database did not confirm may have been recorded, so repeating it is safe.

Logout to unlink the device from the WhatsApp account — a protocol-level unlink, unlike stop or delete:

curl -X POST "http://localhost:2785/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/logout" \
-H "X-API-Key: YOUR_API_KEY"

stop() disconnects but keeps the stored credentials (a later start reconnects without a QR), and delete() additionally purges the on-disk auth directories and the session row — but neither tells WhatsApp anything, so the device stays listed under the account's Linked Devices on the phone until you remove it by hand. logout sends the engine-native unlink (remove-companion-device on Baileys, Client.logout() on whatsapp-web.js) and then tears the session down locally.

StatusMeaning
200Engine-native unlink and required local credential cleanup both completed; the session is stopped, phone is cleared, and the audit log records session_logged_out. Reconnecting after this always requires a fresh QR scan or pairing code.
400The session is not started — there is no engine to send the unlink through; the row is left untouched
404Session not found
409On Baileys, the session has no linked device (for example it is still at qr_ready, v0.27.0+): the session is stopped locally, phone is cleared, and no session_logged_out audit row is written.
502The session was stopped locally and phone cleared, but the unlink did not complete (no send, no acknowledgement, timeout/transport error, or local-cleanup failure). Retryable — the body carries code: 'SESSION_LOGOUT_INCOMPLETE', and no success audit row is written. Start the session again and retry.
503The database did not answer the read of the session (v0.31.0+), so nothing was logged out. Retry the logout.

logout requires the session to be started and needs an operator key, like the other write actions.

An unlink done from the phone reaches the same end state from the other side: since v0.23.3 the running engine clears the session's phone when WhatsApp reports the device unlinked, so AUTO_START_SESSIONS no longer relaunches it into a QR nobody asked for on the next restart. The next successful link sets phone again.

On Baileys an unlink also deletes what the gateway stored for the account: the engine's copies of the session's messages (baileys_stored_messages) and the session's chat states (mute, archive, pin). That happens once WhatsApp acknowledges the unlink a logout sends, and equally for an unlink WhatsApp reports. The messages rows stay, so earlier messages still list and search, but a request that needs the stored copy of a message, such as a reply, forward, reaction, edit, delete, star or pin, answers 404 for every message from before the unlink. Since v0.30.1 the engine logs Cleared the stored messages of an unlinked account and Cleared the stored chat states of an unlinked account when each clear completes.

Delete to remove the session entirely with DELETE /api/sessions/:id. It returns 204 No Content with an empty body:

curl -X DELETE "http://localhost:2785/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a" \
-H "X-API-Key: YOUR_API_KEY"

Since v0.26.0 the delete runs in steps, so a session with a long history no longer holds the database in one statement. It first removes the session's messages, webhook outbox records and webhook delivery-failure records in batches (up to 2000 rows per batch on SQLite, 500 on PostgreSQL), each in its own transaction, then everything else together with the session row in a final transaction, then the on-disk auth directories. The batches are not atomic with the rest: a failure after removal has begun (a database error, a timeout, a restart) leaves the session in place with fewer rows and kept down the way a stop keeps it: boot auto-start and the multi-node takeover skip it until an explicit start (the takeover sweep of a v0.25.0 node does not honour that record and can take the session over, so upgrade every node before relying on it). Repeat the DELETE to finish, or call POST /api/sessions/:id/start to keep what remains. Size client and reverse-proxy timeouts for the session's history, since large outbox and delivery-failure tables add time. Besides the 409 and 404 answers in Common errors, a delete answers 409 when another node takes the session over while it runs (rows removed by earlier batches stay removed), and 503 when it cannot claim the session because the database does not answer (nothing is removed) or, on SQLite, when another database transaction stays open for 10 seconds before a step (earlier batches may already be committed, so retry). Since v0.31.0 that 503 also covers a database that does not answer a second read of the session, made once the delete holds its claim, or the write that records the delete: nothing is removed, and a delete whose record the database did not confirm may have been recorded, so repeating it is safe. Also since v0.31.0, a second delete that overlaps one that removes the session answers 404, where it answered a 409 that the session was no longer owned by this node.

Delete is destructive — and purges both engines' credentials

Deleting a session removes its database record and the data stored for it: the message history, bulk batches, persisted chat state, status updates, webhooks with their outbound delivery records, both delivery-failure queues, templates, automation rules, send idempotency keys, and stored Baileys messages. The audit log, conversation mappings, ingress events and LID mappings are kept. The media store is not touched: the session's received-status media (statuses/<sessionId>/) and archived chat media (chat-media/<sessionId>/) stay on disk or in the S3 bucket until the orphan sweeps remove them, and no route serves them meanwhile. With the default settings that takes one to two hours (three at most when a pass falls just short of the grace window), longer after a gateway restart in between or when statuses/ or chat-media/ holds more than 100000 unreferenced files (each further 100000 goes one sweep later). It also purges both engines' on-disk auth directories (data/baileys/<id> for Baileys, data/sessions/session-<id> for whatsapp-web.js), keyed by the session id since v0.23.5 and regardless of which engine last ran the session, so a session that ever ran under both engines no longer keeps the other engine's credentials on disk, where they could silently re-link on an engine switchback (and were carried into backups). If an auth path is a symbolic link, since v0.28.0 the delete unlinks the symlink itself (action=engine_purge_link) without touching its target. Up to v0.23.4 the same directories were keyed by session name; the first boot on v0.23.5 renames each one onto its session's id, and a delete still removes a leftover name-keyed directory when one is really on disk (on PostgreSQL since v0.26.0; before, a failed id lookup left it behind). Because a recreated session gets a new id, recreating one under the same name forces a fresh link. Start-time purge is deliberately unchanged, so trialling the other engine on a live session keeps the previous link for rollback. To pause an integration and resume it later with the same linked account, stop the session instead of deleting it.

A delete made while the gateway ran v0.23.5 or v0.23.6 did not purge those directories (fixed in v0.23.7); the upgrade notes describe what it left.

Read and change a session's config​

Four settings are tunable on a session that is already running: whether incoming calls are auto-rejected, the two auto-reconnect knobs, and, since v0.30.3, the default link preview of a text or template send. Since v0.14.5 the first three can be changed in place — before that they were fixed at create time, so turning one on meant creating a new session and linking the account again.

GET /api/sessions/:id/config returns the effective configuration. The values are resolved through the same clamp the engine applies, so a stored value that is out of range reports what will actually happen rather than what was written:

curl "http://localhost:2785/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/config" \
-H "X-API-Key: YOUR_API_KEY"

Response 200:

{
"autoRejectCalls": false,
"maxReconnectAttempts": null,
"reconnectBaseDelay": 5000,
"linkPreview": null
}
FieldTypeDefaultMeaning
autoRejectCallsbooleanfalseDecline every incoming call as soon as it rings. The call.received webhook event still fires first, so a consumer sees the call either way. Baileys only: whatsapp-web.js cannot reject a call, so there each attempt fails and logs a call_auto_reject_failed warning (before v0.23.6 it logged a success while the call kept ringing), and call.received itself is not reliable on that engine.
maxReconnectAttemptsinteger | nullnullCap on consecutive attempts of the gateway's own reconnect: every reconnect on whatsapp-web.js, and on Baileys only the one after a logged-out close (see Auto-reconnect mechanics). null means unlimited; 0 disables that reconnect outright.
reconnectBaseDelayinteger5000Base of the gateway reconnect's exponential backoff, in milliseconds. The Baileys engine's internal retry keeps its own 1-second to 60-second backoff.
linkPreviewboolean | nullnullSince v0.30.3. The link preview of a send-text or send-template that sets neither linkPreview nor customLinkPreview; a value in the request always wins. false sends without a preview on both engines. true asks for one: that is already the default on whatsapp-web.js, and on Baileys it makes the gateway fetch the first https:// link with a domain-name host in the text before the message is sent. null leaves the engine's own default (a preview on whatsapp-web.js, none on Baileys).

Reading the config accepts any valid key except one restricted to chats, which answers 403 API key is restricted to selected chats (v0.23.6+). Writing it — PATCH /api/sessions/:id/config — needs an operator key, like the other write actions.

The patch is a three-state merge​

PATCH merges the keys you send into the stored config rather than replacing it, and each of the four fields carries three distinct meanings:

What the body carries for a fieldWhat happens
The key is absentThe stored value is left unchanged.
The key is present with an explicit nullThe key is cleared, and the field returns to its default.
The key is present with a valueThe value is set.
curl -X PATCH "http://localhost:2785/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/config" \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "autoRejectCalls": true }'

Response 200 — the full effective configuration after the merge, not just the field you sent:

{
"autoRejectCalls": true,
"maxReconnectAttempts": null,
"reconnectBaseDelay": 5000,
"linkPreview": null
}
Unlimited reconnects are reachable only through an explicit null

maxReconnectAttempts accepts 0–20, and every one of those values is a finite cap — 0 does not mean unlimited, it turns the gateway's own reconnect off (on Baileys the engine still retries a network drop itself; see Auto-reconnect mechanics). The default, unlimited, has no in-range number that expresses it, so the only way back to it is an explicit null:

curl -X PATCH "http://localhost:2785/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/config" \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "maxReconnectAttempts": null }'

Omitting the key instead leaves the existing cap in place. A client that strips null fields when it serializes JSON cannot make this call at all.

reconnectBaseDelay accepts 1000–300000 ms. A value outside either range returns 400, as does an unknown body field; an unknown session id returns 404. Since v0.24.0, when concurrent updates to the same session keep conflicting, it returns 409 (Session config is being changed by other requests; retry) and writes nothing, so send the same patch again. Every accepted patch writes a session_config_updated audit row recording the resulting configuration — the merged state, not the request.

When a change takes effect​

No restart happens and none is required, but the four fields do not land at the same moment:

FieldTakes effect
autoRejectCallsOn the next incoming call — the value is re-read per call, so the write alone is what applies it.
maxReconnectAttemptsOn the next session start. A reconnect sequence already in flight keeps the budget it began with.
reconnectBaseDelayOn the next session start, for the same reason.
linkPreviewOn the next send-text or send-template: the value is read on every such send, so the write alone is what applies it.

The Dashboard exposes autoRejectCalls as a toggle on the session detail panel, so that one setting does not need an API call at all.

Running multiple sessions​

One OpenWA instance runs several sessions concurrently — there is nothing to enable. Create each session with its own unique name, start it, and link it to a different WhatsApp number. Each session is fully isolated: its own connection, chats, message history, and webhooks.

An optional MAX_CONCURRENT_SESSIONS env var caps how many WhatsApp engines may run or initialize at once (default 0 = unlimited). A start over the cap answers 400 (Maximum concurrent sessions reached (N)). A session that fails terminally does not hold its slot: both terminal paths evict the dead engine as they mark the session failed, so the capacity comes back on its own and the next start boots clean. Below the cap, the practical limit is the host's memory: the live engine for each session is held in-process, so plan capacity by RAM. The whatsapp-web.js engine is heavier (it drives a headless Chromium) than the browser-free Baileys engine. For provisioning guidance, see Scaling.

Address a session by id​

Every session-scoped route is keyed by the session id in the path. The same call against two different ids acts on two different WhatsApp accounts:

GET /api/sessions/{sessionId}
POST /api/sessions/{sessionId}/messages/send-text
GET /api/sessions/{sessionId}/groups
POST /api/sessions/{sessionId}/webhooks
GET /api/sessions/{sessionId}/catalog

The product catalog routes are keyed the same way, so a business number's catalog belongs to the session that linked it. So to send from a specific number, put that session's id in the URL. To restrict a key to a subset of sessions, set its allowedSessions list (see Authentication), a scoped key only ever touches the sessions it should, and since v0.24.0 a request outside that scope is rejected with 403.

Since v0.23.6 a key can also be restricted with allowedChats. It may read a single session, filtered chats/groups/contacts and stored messages for an explicitly allowed chatId; it may perform the permitted actions on its own chats. Group detail/settings and built-in search are also scoped in v0.25.0. Session discovery, stats, config, proxy, lifecycle, webhook and catalog routes still refuse it with 403. A chat outside the list answers 403 API key not authorized for this chat.

In v0.25.0 the key can subscribe to chat WebSocket events, but session status events remain unavailable. Poll GET /api/sessions/{sessionId} to follow readiness. See Authentication for the complete route model.

Monitor every session at once​

GET /api/sessions/stats/overview returns an aggregate view across the key's sessions — useful for a health panel when many run on one instance:

curl "http://localhost:2785/api/sessions/stats/overview" \
-H "X-API-Key: YOUR_API_KEY"

Response 200:

{
"total": 4,
"active": 2,
"ready": 2,
"disconnected": 1,
"byStatus": { "ready": 2, "disconnected": 1, "created": 1 },
"memoryUsage": { "heapUsed": 142, "heapTotal": 210, "rss": 318 }
}

active counts running engines; byStatus is keyed by the lowercase status values; memoryUsage values are in megabytes. A scoped key sees only the sessions in its allowedSessions. To list every session (not just counts), use GET /api/sessions, which returns a bare array ordered by createdAt descending and takes limit and offset. Since v0.23.5 it also takes name, an exact, case-sensitive filter that returns just that one session, so resolving a known name to its id no longer means pulling the whole list. The filter is ANDed with the key's allowedSessions, so a name outside a scoped key's allowlist answers 200 with an empty array, exactly as an unknown name does; an empty name or a repeated name key answers 400 rather than being ignored. For per-session message stats, GET /api/stats/sessions/:id returns top chats with a lastActive formatted as YYYY-MM-DD HH:MM:SS consistently on both SQLite and PostgreSQL.

Own global presence (v0.15.0+)​

Set whether the linked account appears online or offline to other WhatsApp users with PUT /api/sessions/:id/presence. This is connection-scoped — since v0.24.0 the gateway re-applies it each time the same engine's connection reopens, which covers a Baileys transient reconnect, but a restart, a Stop and Start, or any other reconnect replaces the engine and drops it, so issue it again then.

# Appear online (suppresses the phone's own notifications)
curl -X PUT "http://localhost:2785/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/presence" \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "available": true }'
# Go offline (hands notifications back to the phone)
curl -X PUT "http://localhost:2785/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/presence" \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "available": false }'

Response 200 for both directions:

{
"success": true
}
FieldTypeMeaning
availablebooleantrue marks the session online; false marks it offline. Required. Only a real boolean or the exact strings "true" / "false" are read — any other value fails validation with 400 rather than being coerced.

Publishing presence needs an operator key, like the other write actions. The statuses:

StatusMeaning
200Presence published
400The session was never started, so there is no engine to publish through — or available failed validation
404Session not found
409An engine exists but is not ready (disconnected, reconnecting, or initializing), so the request never reached WhatsApp — wait for ready and retry. On Baileys it also answers while a ready session's account profile name has not synced yet (since v0.24.0; before, the call answered 200 without publishing anything; since v0.27.0 Baileys updates the session's pushName as soon as the newly linked account syncs it, so you do not need to restart the session once the name arrives): nothing was sent, so retry once the name has synced. On whatsapp-web.js it also answers, since v0.26.0, when WhatsApp Web reloads its page while the call runs, and since v0.31.0 that 409 carries code: "ENGINE_PAGE_RELOADING" and retryAfterSeconds; publishing the same presence again is safe
503On whatsapp-web.js, the page connection died or WhatsApp Web did not answer within the protocol timeout. Nothing was confirmed, and publishing the same presence again is safe

An always-online headless bot suppresses the phone's own push notifications. Setting available: false hands them back. Both engines support this route.

Connection-scoped

Presence is not persisted. Since v0.24.0 a Baileys transient reconnect keeps it, but when the engine is replaced (a stop, a restart, a gateway reconnect, a watchdog recycle or a takeover by another node) the session falls back to its engine default, so re-issue the call in your session.status → ready handler if you need a permanent posture.

Chat operations (v0.16.0+)​

Two chat-level write routes hang off the session: pin a chat to the top of the list, and mute its notifications. Both need an operator key (an admin key also passes; a viewer key is refused with 403 Insufficient permissions. Required: operator), and both address the chat by its JID in the form localpart@host — 628123456789@c.us for a contact, 120363021234567890@g.us for a group. A value without an @ is rejected with 400 chatId must be a valid chat JID in the form localpart@host. Since v0.28.0 the session in the path is checked against [A-Za-z0-9-]{1,128} first and then looked up: a value outside [A-Za-z0-9-]{1,128} answers 400, while a session name (which matches [A-Za-z0-9-]{1,128} but is not a stored session id) answers 404 with a hint pointing to GET /api/sessions?name=<name>. Since v0.23.6 a key restricted to chats (allowedChats) can call both routes only for a chat in its list; any other chatId answers 403 API key not authorized for this chat. That check follows the role check and comes before the session id is parsed (see Address a session by id). Also on Baileys, since v0.28.0 GET /api/sessions/:id/presence/:chatId finds presence stored under a contact's @lid when queried by phone number once an engine has reported the pair.

The failure statuses are the same on both: 400 when the session was never started (no engine to send through) or the body is invalid, 404 when the session id is unknown, 409 when an engine exists but is not ready (disconnected, reconnecting, or initializing) or, on whatsapp-web.js since v0.26.0, when WhatsApp Web reloads its page while the call runs (since v0.31.0 that 409 carries code: "ENGINE_PAGE_RELOADING" and retryAfterSeconds, the interval to ask again at: a reload can last a few minutes and no event marks its end), and 503 when WhatsApp did not answer within the request budget — after a 503 the change may or may not have been applied. See API conventions for the shared meaning of those statuses.

Pin or unpin a chat​

POST /api/sessions/:id/chats/pin pins a chat to the top of the list, or releases one that is already pinned.

# Pin a group chat to the top of the list
curl -X POST "http://localhost:2785/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/pin" \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "120363021234567890@g.us", "pin": true }'

Response 200:

{
"success": true
}
FieldTypeMeaning
chatIdstringJID of the chat to act on, in the form localpart@host. Required; null is not accepted.
pinbooleantrue pins the chat to the top of the list, false unpins it. Required. Only a real boolean or the exact strings "true" / "false" are read — any other value fails validation with 400 rather than being coerced, so a stray string cannot be taken as true and pin a chat you asked to release.

Both engines support this route.

success: false is the three-pin cap, not "chat not found"

WhatsApp allows at most three pinned chats. success: false means that cap refused a real chat, and only the whatsapp-web.js engine reports the refusal — Baileys cannot observe the cap and always answers success: true. Unpinning always succeeds.

A chat the session cannot resolve is a different answer entirely: on whatsapp-web.js it is a 400 (Chat <chatId> does not exist on this session), while on Baileys, since v0.28.0, pinning or muting a 1:1 chat requires the contact's phone number and @lid privacy id to be paired in lid_mappings (WhatsApp's app-state sync addresses 1:1 chats by LID) and answers 400 when the contact has no known LID pairing yet; for a paired 1:1 chat or a group, Baileys writes the state without resolving the chat ahead of the write. Since v0.23.6, when the whatsapp-web.js page does not answer that chat lookup in time, the route answers 503 instead of the 400; earlier releases answered the 400 then, even for a chat that exists. A page reload that cuts the lookup short answers 409 instead (v0.26.0+).

Mute or unmute a chat​

POST /api/sessions/:id/chats/mute silences a chat until a timestamp you choose, or lifts an existing mute.

# Mute until an absolute epoch-milliseconds timestamp
curl -X POST "http://localhost:2785/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/mute" \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "120363021234567890@g.us", "muteUntil": 1800000000000 }'
# Unmute now — an explicit null, not an omitted field
curl -X POST "http://localhost:2785/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/mute" \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "120363021234567890@g.us", "muteUntil": null }'

Response 200 for both directions:

{
"success": true
}
FieldTypeMeaning
chatIdstringJID of the chat to act on, in the form localpart@host. Required; null is not accepted.
muteUntilnumber | nullAbsolute epoch milliseconds at which the mute expires, or null to unmute now. Required. A value above 9007199254740991 (Number.MAX_SAFE_INTEGER) answers 400 since v0.26.0.

Unlike the pin route there is no declined outcome here — a 200 always carries { "success": true }. The mute change is not keyed to the chat's last message on either engine, so a chat with no known history mutes like any other. Both engines support this route. A chat the session cannot resolve is a 400 on the whatsapp-web.js engine (since v0.23.6 a lookup the page does not answer in time is a 503 instead, where earlier releases answered the 400, and since v0.26.0 a page reload that cuts it short is a 409); on Baileys, since v0.28.0 a 1:1 chat whose phone number and @lid are not paired in lid_mappings also answers 400, while a paired 1:1 chat or a group writes the mute without resolving the chat first, the same split the pin route's caution above describes. On whatsapp-web.js a channel id (@newsletter) is also a 400, since v0.31.0: mute or unmute a channel through its own route, POST /api/sessions/:id/channels/{channelId}/mute.

muteUntil is required, and it is milliseconds

Omitting muteUntil returns 400; it is not guessed. The two plausible readings of a missing field — unmute now, or mute forever — are opposites, so the gateway refuses to pick one. Only an explicit null unmutes. There is no "mute forever" sentinel either: to mute indefinitely, send a far-future timestamp, no later than 9007199254740991.

The value is epoch milliseconds, unlike the epoch seconds OpenWA uses for message timestamps (see API conventions). A seconds-scale value passes validation and still answers 200, but it points at an instant in 1970, so the mute expires the moment it is written.

Read the state back (v0.23.4+)​

The pin, mute and archive routes have existed for releases, but nothing reported the result. Since v0.23.4 every chat summary carries its own state, on GET /api/sessions/:id/chats and, on whatsapp-web.js only, on GET /api/sessions/:id/labels/:labelId/chats (Baileys answers 501 there):

{
"id": "120363021234567890@g.us",
"name": "Release Team",
"isGroup": true,
"kind": "group",
"unreadCount": 3,
"timestamp": 1786000000,
"lastMessage": "See you then",
"archived": false,
"pinned": true,
"muted": true,
"muteExpiration": 1786003600000
}
FieldTypeMeaning
archivedbooleanArchived state, as set by POST /chats/archive with { "chatId": "…", "archive": true }. Always present.
pinnedbooleanPinned state, as set by the pin route above. Always present.
mutedbooleanWhether the chat is muted right now, not whether a mute was ever set. Always present. whatsapp-web.js derives it from the page; on Baileys the gateway compares the stored end time against the current instant.
muteExpirationnumberEpoch milliseconds at which the mute ends. Present only when muted is true; 0 means muted indefinitely.

muteExpiration uses the same unit as muteUntil, so a finite value can be written straight back to re-apply the same mute. The 0 of an indefinite mute is the one exception: muteUntil demands a real future instant and rejects 0, so re-apply an indefinite mute with a far-future timestamp instead.

Since v0.31.0 a Baileys chat that WhatsApp holds under a privacy id (@lid) and that has no saved, verified or push name lists name as "", where it used to list the id's own digits, which are not a phone number. When the session can map the id, the row carries phone, the number's digits: title such a chat by phone, else by id. A saved name still wins over it. A phone-keyed chat carries no phone because its id is the number, and neither does a privacy-id chat the session cannot map. Every Baileys name is trimmed, and a blank name of any other chat lists the contact's name or the id's digits. whatsapp-web.js lists no phone and lists a chat the page gives no title under its own id as name.

Since v0.26.0 a chat list request with offset above 0 reuses the list that the first page of the walk read, for up to 5 seconds, so later pages can lag a change made elsewhere (on the phone, for one) by that much. The first page always reads fresh, and the pin, mute and archive routes drop the reused list.

On Baileys these three are persisted per chat and rehydrated at boot, because WhatsApp does not re-deliver them, so they survive a reconnect or a process restart (an unlink clears them, see Stop or delete a session). Since v0.28.0, after a gateway restart, GET /api/sessions/:id/chats on Baileys also seeds the session's chat list from stored messages (up to BAILEYS_SESSION_STORE_MAX_ENTRIES, default 5,000) in addition to chat_states, so unpinned, unmuted, unarchived chats with stored message history stay listed before new messages arrive. Since v0.27.0 the Baileys chat actions (POST /chats/read, POST /chats/unread, POST /chats/archive, POST /chats/clear, and DELETE /chats/{chatId}) also fall back to the newest message stored in the gateway database when the session holds none in memory, and deleting a Baileys chat records chat_states.deletedAt so the chat stays out of GET /chats (and those actions answer success: false) until a newer message re-creates it. On whatsapp-web.js they are read from the live page each time. chat_states is part of the export/import set, so a data migration carries them across.

On Baileys, since v0.31.0, a POST /chats/read whose receipt names the chat's newest received message sets that chat's unreadCount back to 0 and also undoes an unread mark set by hand (POST /chats/unread or on the phone); before, the count and the mark stayed, so an unread badge came back on every reload. With STORE_EPHEMERAL_MESSAGES=false, Baileys lists a chat with an empty lastMessage while its newest message is one it received in a disappearing-messages chat (since v0.31.0), whereas whatsapp-web.js still returns it, because WhatsApp Web holds the message until it expires.

archived, pinned and muted are required fields

All three are non-optional on ChatSummary. Generated clients and SDK types set them, but a hand-written ChatSummary fixture, mock or stub in your own tests has to supply all three or it no longer matches the contract. GET /labels/{labelId}/chats (whatsapp-web.js only; Baileys answers 501) is affected too: it used to return a narrower object of its own and now returns the same ChatSummary as the chats list. Since v0.31.0 its rows also carry lastMessage, as the chats list does.

POST /api/sessions/:id/calls/link asks WhatsApp for a link that anyone can open to join a call with the linked account. Success is 200, not 201, and the body carries the finished URL. The route needs an operator key.

# A video call link for a scheduled call
curl -X POST "http://localhost:2785/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/calls/link" \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "type": "video", "startTime": 1800000000000 }'

Response 200:

{
"link": "https://call.whatsapp.com/video/XxXxXxXxXxXxXx"
}
FieldTypeMeaning
type"audio" | "video"Which kind of call the link opens. Required. "video" yields a https://call.whatsapp.com/video/<token> URL; "audio" yields https://call.whatsapp.com/voice/<token> — WhatsApp's own path segment for an audio call is voice, not audio.
startTimenumberAbsolute epoch milliseconds at which the call is scheduled to start. Required: the whatsapp-web.js engine generates an event-linked call and has no notion of "no start time", so a link for right now is Date.now() rather than an omitted field.

Both fields are required and neither accepts null. An invalid type or startTime, or a session that was never started, returns 400; a session whose engine is present but not ready returns 409. Since v0.23.4 this route declares no 5xx at all: it used to answer 503 when WhatsApp did not answer, and a 503 is replay-safe in every client, so a retry could mint a second link. A failure now surfaces as an opaque 500 and the outcome is genuinely unknown, so read the chat or your call links back rather than repeating the request. Both engines support this route — they differ only in the unit they are called with internally (Baileys in seconds, whatsapp-web.js as a Date), which is invisible on the wire: the API takes milliseconds on both.

A failed generation is a 403, not a 200 with an empty link

When WhatsApp produces no link, the gateway answers 403 WhatsApp did not return a call link instead of a success carrying an empty link. Both engines can reach that case — whatsapp-web.js resolves an empty string on a generation failure, and Baileys can resolve an empty token — and a bare https://call.whatsapp.com/video/ prefix with nothing after it would be a dead link that looks real. So every 200 carries a usable URL, and the failure to branch on is 403.

Lifecycle with the SDK​

The @rmyndharis/openwa SDK 0.13.0 wraps the session routes on this page, including getProxy, updateProxy and the sessions.list({ name }) filter. See SDK usage for proxy examples. Construct the client with your gateway's base URL without the /api suffix, which the resource methods add themselves:

import { OpenWAClient } from '@rmyndharis/openwa';

const client = new OpenWAClient({
baseUrl: 'http://localhost:2785',
apiKey: 'YOUR_API_KEY',
});

const session = await client.sessions.create({ name: 'my-bot' });
await client.sessions.start(session.id);

// Show the QR, then poll until the session reports ready.
const { qrCode } = await client.sessions.getQrCode(session.id);
console.log('Scan this QR:', qrCode);

let status = (await client.sessions.get(session.id)).status;
while (status !== 'ready' && status !== 'failed') {
await new Promise((r) => setTimeout(r, 2000));
status = (await client.sessions.get(session.id)).status;
}
console.log('Session status:', status); // "ready"

To link by phone instead of QR, call client.sessions.requestPairingCode(session.id, { phoneNumber: '628123456789' }). Aggregate stats are client.sessions.stats(). The config routes are client.sessions.getConfig(id) and client.sessions.updateConfig(id, { autoRejectCalls: true }). See SDK usage for the full surface.

Account restrictions​

WhatsApp itself can impose limits on a linked account that are not faults on our side and not engine failures — they are server-side enforcement the gateway observes and surfaces. Since v0.14.0 these appear on the session instead of as a generic send or connect error, so you can branch on them.

A restriction is reported on the session's restriction field (added to the response of every read route and to the create/start payloads), with the shape:

FieldTypeNotes
kindreachout_timelock | tos_block | proxy_block | passkey_requiredWhat WhatsApp is restricting. reachout_timelock leaves the session connected and existing chats working, blocking only the start of new conversations. tos_block and proxy_block are connection-level refusals, so they never coexist with status: ready. passkey_required (v0.30.0+, Baileys only, code: "passkey_prologue_request", expiresAt: null) is set when WhatsApp asks for a passkey to finish linking a device, which Baileys cannot complete; the session stays at qr_ready and the restriction lifts when a link reaches ready (stop, start, or logout does not clear it; deleting the session or restarting the gateway drops it).
codestringThe engine's own token for the cause, passed through verbatim so you can search for it and so a value newer than this gateway is still surfaced rather than flattened.
expiresAtstring (date-time) | nullWhen enforcement ends, if the engine states it. Only reachout timelocks carry an expiry; absent means the engine gave no end time, not that the restriction is permanent.

When no restriction is in force, restriction is null. The field reflects live engine state held in the gateway's memory and is never persisted — it is re-established on the next connect. A gateway restart drops it, and the engine reports it again when it still applies (a passkey_required returns only when WhatsApp asks for the passkey again on a new link). A stop, start or logout does not drop it. What ends a restriction is a lift the engine reports, a link that reaches ready (for tos_block, proxy_block and passkey_required, which a linked session cannot carry; a reachout_timelock survives ready), the passing of its expiresAt, or deleting the session.

The same change is delivered through two live channels:

  • Webhook: a session.restriction event fires on each onset and lift. The event is idempotency-keyed per session and per restriction fact, and salted so a restriction that lifts and later returns is not deduped away as a replay.
  • WebSocket: session.restriction is socket-subscribable as well as webhook-delivered (since v0.14.0). The dashboard session card picks up a restriction (or its lift) live from the socket and shows a badge, with no page reload.

The audit log records session_restricted (WARN) when a restriction is detected and session_restriction_lifted when one ends, and the openwa_sessions_restricted Prometheus gauge counts sessions with an active restriction (passkey_required included). OpenWA cannot lift a restriction WhatsApp has imposed — for tos_block in particular, the account itself needs an appeal through WhatsApp's own channels.

Common errors​

StatusWhenFix
400 Bad RequestInvalid name, a config object over 16,384 serialized bytes on create (v0.28.0+), a pairing phoneNumber that is not 6 to 15 digits, extra body field, QR fetched before qr_ready, a session :id outside [A-Za-z0-9-]{1,128} (since v0.28.0 an unknown id that matches [A-Za-z0-9-]{1,128}, such as a session name, answers 404 instead of 400), a proxyUrl whose credentials hold a % that begins no valid percent-escape on create or PATCH /proxy (v0.23.6+), force-kill on a session with no live engine, logout on a session that is not started, or a start of a session that is already running or starting, or over the MAX_CONCURRENT_SESSIONS capMatch the field rules; start the session before fetching the QR; pass the id returned by create; write a literal % in proxy credentials as %25; for a stale row use stop instead of force-kill; start the session before logging out; for a refused start, read engineLoaded on the session, or stop another session or raise MAX_CONCURRENT_SESSIONS
401 UnauthorizedMissing, invalid, revoked or expired X-API-KeySend a valid, active key
403 ForbiddenSince v0.24.0 a valid key used on a session outside its allowedSessions, or from an address outside its allowedIps (earlier releases answered 401). A valid key whose role is below operator on an operator-gated route — the write actions (create, start, stop, delete, logout) plus fetching the QR (GET /qr) and requesting a pairing code. Since v0.12.0 a session-restricted key is also refused on deployment-global surfaces (most notably PUT /api/plugins/:id/sessions), and on POST /api/sessions and PATCH /api/sessions/{sessionId}/proxy (v0.23.4+). Since v0.23.6 a key restricted to chats (allowedChats) is refused on every route not open to it, and on the open ones for a chat outside its list. Since v0.24.0 a key below admin is also refused when it sets proxyUrl on create or calls PATCH /api/sessions/{sessionId}/proxyUse a key whose allowedSessions and allowedIps cover the request; use an operator (or higher) key; use an unscoped key to create a session, change a session proxy, or manage plugin activation, and an admin key to set a proxy; use a key without a chat restriction for session management
404 Not FoundThe session id does not existCheck the id from the create response
409 ConflictA session with that name already exists (a name that loses a create race to an identical one also returns 409, not 500). Since v0.12.0, POST /sessions/:id/start and DELETE /sessions/:id can also answer retryable 409 with code: 'SESSION_NAME_TEARDOWN_PENDING' while a name-keyed credential teardown is still in flight. A start also answers 409 when another node holds the session's engine and, with no code, when a stop, a logout (since v0.26.0) or force-kill that found an engine to kill, or a data import of the session began or finished while the start was waiting (see Start the session). A delete answers 409 when another node takes the session over while it runs (see Stop or delete a session). On Baileys, POST /sessions/:id/logout answers 409 when the session has no linked device (stopped locally, phone cleared, no session_logged_out audit row, v0.27.0+). POST /sessions/:id/pairing-code answers 409 for an unrelated reason: the session is not waiting to be linked yet, or, on whatsapp-web.js since v0.26.0, the number is the stored phone of another sessionPick a unique name, or reuse the existing session; for the teardown 409, wait a short delay and retry; for a start that lost to a stop, send it again; for the pairing 409, wait for qr_ready (or for ready, if a code was already accepted) and try again, or, for a number another session holds, delete or log out that session first or link by QR. No destructive side effect ran before the refusal
429 Too Many RequestsThe request rate limiter (RATE_LIMIT_*) shed the request. The body is { statusCode, message } with no error field, and since v0.23.6 a Retry-After header gives the seconds to wait. The routes on this page are not covered by send pacingWait for Retry-After, then retry
503 Service UnavailablePOST /sessions/:id/pairing-code on whatsapp-web.js ran out of attempts, each failed or timed out, usually because WhatsApp Web kept reloading its QR page (v0.23.6+; a 500 before). POST /sessions/:id/start also answers 503 while the gateway is shutting down, or when the engine's browser or socket died during launch and the one automatic retry failed too. Since v0.26.0, on SQLite, POST /sessions and DELETE /sessions/:id answer 503 when another database transaction stays open for 10 seconds (a create stores nothing; a delete may already have committed earlier batches), and DELETE /sessions/:id also answers it when it cannot claim the session (nothing is removed). Since v0.31.0 POST /sessions/:id/stop, POST /sessions/:id/logout and POST /sessions/:id/force-kill also answer it when the database does not answer the read of the session before they act, DELETE /sessions/:id also when it does not answer the read of the session it makes once it holds its claim, and a stop or delete also when the database does not answer the write that records it (nothing was stopped, logged out, killed or deleted, and repeating the request is safe)Retry shortly; read the pairing warning first if the number is linked elsewhere
504 Gateway TimeoutPOST /sessions/:id/start: the engine did not finish starting within its timeoutRetry; the engine was torn down. See Start the session for the causes

For a wider catalogue of failures and recovery steps, see Troubleshooting.

Next steps​

  • Sending messages — text, media, and the recipient JID format.
  • Webhooks — react to inbound messages and session.status changes instead of polling.
  • First session — the end-to-end walkthrough from zero.
  • API reference — every session field, query parameter, and status code.