Connect a session
By the end of this tutorial you will have a WhatsApp account linked to OpenWA and a test message delivered from it. The path is four steps: create a session, start it, scan its QR code, then send a message.
A session is one linked WhatsApp account. One OpenWA instance runs many sessions side by side, each identified by its own UUID.
Quick Start walks the same four steps in their shortest form. This page is the longer version: every status the session passes through, the dashboard route as well as the API one, and what to do when a step does not go as written.
- OpenWA running locally — see Installation. This tutorial uses the base URL
http://localhost:2785/api. - An API key with at least the
operatorrole and neither a session restriction (allowedSessions) nor a chat restriction (allowedChats, v0.23.6+). Creating, starting, and sending all requireoperator, and a key restricted to sessions cannot create a session; the seeded admin key works. See Authentication for where the key comes from. - WhatsApp installed on a phone you can scan a QR code with.
Every request below sends your key in the X-API-Key header. Export it once so the examples are copy-paste runnable:
export API_KEY="YOUR_API_KEY"
How a session connects
A session moves through a fixed set of states from creation to connected. You drive the first two transitions with API calls; WhatsApp drives the rest once you scan.
The status field on a session is always one of these lowercase values:
| Status | Meaning | What you do |
|---|---|---|
created | Session exists; the engine has not started. | Call start. |
initializing | Engine is starting and contacting WhatsApp. | Wait, then fetch the QR. |
qr_ready | A QR code is available to scan. | Scan it with your phone. |
authenticating | QR scanned; the link handshake is finishing. On Baileys the session passes back through initializing before ready, because WhatsApp asks for a restart as soon as it accepts the link (since v0.23.3). | Wait. |
ready | Connected. The session can send and receive. | Send a message. |
action_required | Connected, but the engine needs a human before the session is usable, for example a whatsapp-web.js onboarding modal it could not dismiss. lastError carries the reason. | Read lastError, do what it asks, then stop and start the session. |
disconnected | Link closed (you stopped it, or it dropped). Usually reconnects without a new QR. | Restart if needed. |
failed | Terminal error (for example, the link was rejected). lastError explains it. | Inspect lastError, then retry. |
You have two ways to walk this flow: the dashboard, which renders the QR for you, or the API. Pick one — both reach the same ready state.
If the number you are about to link is fresh, let it behave like a normal user for a few days before any heavy sending — see Ban risk & safe sending.
Option A — connect via the dashboard
The dashboard runs on the same port as the API. Use it if you want to scan without scripting anything.
- Open
http://localhost:2785and sign in with your API key. - Go to Sessions and choose New Session. Give it a name (letters, numbers, and hyphens; 3–50 characters).
- Start the session. A live QR code appears once the status reaches
qr_ready. Since v0.23.6 the dashboard opens no QR window for a session that comes back from the start alreadyready, and a start that fails without leaving an engine shows the gateway's error in a toast instead of a QR window that never fills. - On your phone, open WhatsApp → Settings → Linked devices → Link a device and point the camera at the QR.
- Watch the status badge advance through
authenticatingtoready.
Fresh QR codes are pushed to the dashboard over its WebSocket connection, so an expired code is replaced for you without a page reload. Since v0.23.6 the dashboard also blanks the code when the session's status turns disconnected, so a code from a connection that is gone is not left on screen to scan, and it closes the QR window when the session fails or disconnects with no engine left. On Baileys a socket that drops while the QR waits reports initializing instead, so its old code stays on screen until the reconnected socket pushes a new one.
The connect modal also has a Link with Phone Number tab. Enter the number in international format (digits only) and the dashboard requests an 8-character pairing code to type into WhatsApp under Link a device → Link with phone number — useful on a headless server or when you cannot scan a QR.
Since v0.26.0 a pasted number written with a plus, spaces, hyphens, dots or parentheses is read to its digits; one with more than 15 digits, or with any other text, is refused with the field error and requests no code.
On the whatsapp-web.js engine, a code requested for a number that already has a linked session can make WhatsApp unlink that device, and since v0.23.6 the tab warns about it. Since v0.26.0 the gateway also refuses, with 409, a number that is the stored phone of another session. Link by QR if that session must stay up; see Sessions.
For a full tour of the interface, see the dashboard guide. The rest of this tutorial uses the API.
Option B — connect via the API
1. Create the session
POST /api/sessions registers a session. Only name is required — letters, numbers, and hyphens, 3 to 50 characters.
curl -X POST http://localhost:2785/api/sessions \
-H "Content-Type: application/json" \
-H "X-API-Key: $API_KEY" \
-d '{ "name": "my-bot" }'
A 201 Created returns the new session. Its status is created and it has a UUID id you use in every later call:
{
"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 for the rest of the tutorial:
export SESSION_ID="8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a"
A duplicate name returns 409 Conflict. A name outside the allowed length or character set returns 400.
DELETE /api/sessions/{sessionId} now also removes the engine's on-disk auth directory
(data/baileys/<id> for Baileys, data/sessions/session-<id> for whatsapp-web.js; the
directories are keyed by the session's UUID id rather than its name since v0.23.5), not just
the database rows — and it removes the session's message history, webhooks, templates, automation
rules and other stored records. Since v0.28.0, an auth directory that is a symbolic link (for example a profile relocated onto another volume) is unlinked as a link only (action=engine_purge_link), leaving its target directory and stored login in place until you remove them by hand. Recreating a session under the same name therefore starts fresh: the new
session gets a new UUID, and the deleted account's credentials are gone from disk. Deletes made
while the gateway ran v0.23.5 or v0.23.6 left them behind, and upgrading does not remove them; the
upgrade notes say what to do about them. Stored
media files are not removed with the session: the orphan sweeps delete its received-status media and
archived chat media one to two hours later with the default settings (three at most), and later after
a restart or when statuses/ or chat-media/ holds more than 100000 unreferenced files, where each further 100000 goes one sweep later (see Configuration). See the
Sessions guide for the full lifecycle.
2. Start the session
POST /api/sessions/{sessionId}/start boots the WhatsApp engine. The response is the session with its status advanced to initializing.
curl -X POST http://localhost:2785/api/sessions/$SESSION_ID/start \
-H "X-API-Key: $API_KEY"
{
"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
}
Starting an already-started session returns 400. Within a second or two the status moves on to qr_ready.
3. Fetch and scan the QR code
GET /api/sessions/{sessionId}/qr returns the current QR as a PNG data URL, plus the session's status.
curl http://localhost:2785/api/sessions/$SESSION_ID/qr \
-H "X-API-Key: $API_KEY"
{
"qrCode": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
"status": "qr_ready"
}
If you get 400 here, the engine has not reached qr_ready yet (or the session is already linked). Wait a moment and retry the same call.
To scan, render qrCode as an image. The fastest way from the terminal is to write the data URL to an HTML file and open it:
QR=$(curl -s http://localhost:2785/api/sessions/$SESSION_ID/qr \
-H "X-API-Key: $API_KEY" | sed 's/.*"qrCode":"\([^"]*\)".*/\1/')
echo "<img src=\"$QR\">" > qr.html
open qr.html # macOS; use xdg-open on Linux
On your phone, open WhatsApp → Settings → Linked devices → Link a device and scan the image. WhatsApp rotates the QR every few seconds, so if it expires before you scan, re-fetch it with the same GET call.
On a headless server, link by phone number instead. POST /api/sessions/{sessionId}/pairing-code with { "phoneNumber": "628123456789" } (digits only, country code first, 6–15 digits) returns an 8-character pairingCode. Enter it under Link a device → Link with phone number on your phone. Request the code only once the session reads qr_ready, the same point the QR becomes available: earlier, the route answers 409 Conflict because the engine is still connecting. On the Baileys engine that 409 can also answer while status still reads qr_ready, for as long as a dropped socket takes to finish closing (up to 30 s), so retry once before treating it as a bad state. Since v0.27.0 Baileys waits five minutes from the latest pairing-code request for the code to be entered before registering again with a new QR; from 60 seconds after the request until that new QR arrives, GET /api/sessions/{sessionId}/qr answers 400 because no QR is ready yet.
On the whatsapp-web.js engine, the route answers 503 since v0.23.6 when every internal retry failed or timed out, usually because WhatsApp Web kept reloading its QR page; the condition is transient, so retry. On that engine, request a code only for a number you are prepared to re-link: a code requested for a number that already has a linked session can make WhatsApp unlink that device. Since v0.26.0 the route answers 409 for a number that is the stored phone of another session of this gateway; delete that session or log it out first, or link by QR.
On the Baileys engine, if the phone answers "Couldn't link device" after you enter the code 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.
4. Confirm it is connected
Poll the session until its status is ready. GET /api/sessions/{sessionId} returns the current state.
curl http://localhost:2785/api/sessions/$SESSION_ID \
-H "X-API-Key: $API_KEY"
Once linked, status is ready and phone carries the connected number:
{
"id": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",
"name": "my-bot",
"status": "ready",
"phone": "628123456789",
"pushName": "My Bot",
"connectedAt": "2026-06-25T09:06:11.000Z",
"lastActive": "2026-06-25T09:06:11.000Z",
"createdAt": "2026-06-25T09:00:00.000Z",
"updatedAt": "2026-06-25T09:06:11.000Z",
"lastError": null,
"restriction": null,
"engineLoaded": true
}
If status is failed, read lastError for the reason, then stop and start the session to retry.
Send a test message
With the session ready, send a text. chatId is the recipient's number in international format — digits only, no + — followed by @c.us. Send to your own number first.
curl -X POST http://localhost:2785/api/sessions/$SESSION_ID/messages/send-text \
-H "Content-Type: application/json" \
-H "X-API-Key: $API_KEY" \
-d '{
"chatId": "628123456789@c.us",
"text": "Hello from OpenWA!"
}'
A 201 Created returns the WhatsApp message id and an epoch-seconds timestamp. It means the gateway handed the message to WhatsApp, not that it was delivered:
{
"messageId": "true_628123456789@c.us_3EB0ABCD",
"timestamp": 1719312000
}
That confirms the full path works: created, started, scanned, connected, sending.
Do it with the SDK
The @rmyndharis/openwa JavaScript SDK wraps the same calls. Note the baseUrl is the origin without the /api prefix — the SDK adds it.
npm install @rmyndharis/openwa
import { OpenWAClient } from '@rmyndharis/openwa';
const client = new OpenWAClient({
baseUrl: 'http://localhost:2785',
apiKey: process.env.API_KEY!,
});
// 1. Create and start
const session = await client.sessions.create({ name: 'my-bot' });
await client.sessions.start(session.id);
// 2. Fetch the QR (render qrCode as an image, then scan)
const { qrCode } = await client.sessions.getQrCode(session.id);
console.log(qrCode); // data:image/png;base64,…
// 3. Poll until ready
let status = 'initializing';
while (status !== 'ready') {
await new Promise((r) => setTimeout(r, 2000));
status = (await client.sessions.get(session.id)).status;
}
// 4. Send a test message
const msg = await client.messages.sendText(session.id, {
chatId: '628123456789@c.us',
text: 'Hello from OpenWA!',
});
console.log(msg.messageId);
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
401 Unauthorized on every call | Missing, invalid, revoked, or expired X-API-Key. | Check the header value and send a valid, active key. See Authentication. |
403 Forbidden on create/start/send | Key role is below operator, its IP or session scope excludes this request, or (on create) it is restricted to sessions (allowedSessions). Since v0.23.6 a key restricted to chats (allowedChats) is also refused on create and start, and on a send to a chat outside its list. | Use an operator or admin key with no session or chat restriction. |
409 Conflict on create | A session with that name already exists. | Pick a different name, or reuse the existing session's id. |
400 on the QR call | Engine has not reached qr_ready, the session is already linked, or on Baileys a pairing code was requested more than 60 seconds ago and the five-minute pairing window has not yet rotated back to a new QR (v0.27.0+). | Wait a moment and retry, enter the pairing code or request a new one, or check status with GET /api/sessions/{sessionId}. |
409 on the pairing-code call | The session is not at qr_ready: still connecting, or a code was already accepted. On whatsapp-web.js, since v0.26.0, also a number that is the stored phone of another session. | Poll GET /api/sessions/{sessionId} until status is qr_ready, then request the code. After a code is accepted, wait for ready instead. For a number another session holds, delete or log out that session first, or link by QR. |
503 on the pairing-code call | whatsapp-web.js only: every internal retry failed or timed out, usually because WhatsApp Web kept reloading its QR page (v0.23.6+; a 500 before). | Retry shortly. |
| Phone answers "Couldn't link device" after a pairing code (Baileys) | Some accounts reject a custom linked-device name. | Remove the override or set BAILEYS_BROWSER_NAME=Ubuntu (the v0.25.0 default), restart OpenWA, and request a fresh code. |
| QR expires before you scan | WhatsApp rotates the code every few seconds. | Re-fetch the QR and scan promptly. |
| The phone asks to create a passkey, or to continue on another device, and linking never completes | WhatsApp requires a passkey step for some accounts, which neither engine implements; the session stays at qr_ready (and on Baileys in v0.30.0+ sets restriction: { kind: "passkey_required", code: "passkey_prologue_request" } and dispatches session.restriction). | No OpenWA-side fix: switching engine or linking by pairing code ends at the same step. See Troubleshooting. |
400 on send-text | The session is not ready, or chatId is malformed. | Confirm status is ready and use <digits>@c.us with no +. |
409 on send-text | An engine exists but is not connected: reconnecting, or on whatsapp-web.js WhatsApp Web reloading its page even while status still reads ready. | Wait for ready and resend. A reload answers with code: "ENGINE_PAGE_RELOADING" and retryAfterSeconds: ask again at that interval, which can go on for a few minutes with no event marking its end. A 409 with no code whose message says the message may or may not have been sent is the exception: check the chat before sending again. |
Status reaches failed | The link was rejected or the engine errored. | Read lastError, then stop and start the session to retry. |
Next steps
- Sessions guide — stop, restart, reconnect, and delete sessions, and run several at once.
- Sending messages — media, replies, reactions, locations, and bulk sends.
- Webhooks — receive incoming messages and status changes in real time.
- API reference — every endpoint, field, and status code.