Repository navigation
Live Chat
Available from v0.8.0, in the React package. The script-tag build does not have live chat yet.
By default the widget hands off to WhatsApp: the visitor fills in the form and WhatsApp opens with a draft. With live chat, the conversation happens inside the widget, and your own backend carries the messages to and from WhatsApp (or anywhere else). Handoff stays the default and needs no backend.
| Handoff (default) | Live chat | |
|---|---|---|
| Visitor ends up in | the WhatsApp app or web | the widget |
| Needs a backend | no | yes: an endpoint that sends and, for replies, one that polls |
| Replies appear | in WhatsApp | in the widget |
| Set with | nothing | transport={...} |
import { WhatsAppChat } from 'whatsapp-chat-widget-react';
import { createWebhookTransport } from 'whatsapp-chat-widget-react/adapters';
// Create the transport once, outside your component, so the same object is used on every render.
const transport = createWebhookTransport({
sendUrl: 'https://n8n.example.com/webhook/chat-send',
pollUrl: 'https://n8n.example.com/webhook/chat-replies',
});
export function Site() {
return <WhatsAppChat phoneNumber="+2348012345678" transport={transport} widgetId="support" />;
}- The usual pre-chat form (name, subject, message, agent picker, AI helpers).
- On submit, the panel changes into a conversation. Their first message is already in the thread.
- A scrollable thread, and a composer at the bottom. Enter sends. Shift+Enter adds a new line.
- Each message they send shows its state: Sending…, Sent, Delivered, or Not sent with a Retry link.
- Replies from your side appear on the left as they arrive.
- A Continue on WhatsApp app link in the header hands the whole conversation to WhatsApp at any time. End chat clears the conversation and returns to the form.
If the page is reloaded, the conversation is still there (see Persistence).
| Prop | Type | Default | What it does |
|---|---|---|---|
transport |
'handoff' | WhatsAppTransportAdapter |
'handoff' |
How a conversation is delivered. An adapter with mode: 'live' turns live chat on. An adapter with mode: 'handoff' behaves like 'handoff'. |
widgetId |
string |
'default' |
Keys the conversation in sessionStorage. Give each widget on a site its own value. |
phoneNumber is optional in live mode. Without one (or an agent number), the Continue on WhatsApp app link is not shown.
An adapter is a plain object, so you can connect anything:
interface WhatsAppTransportAdapter {
mode: 'handoff' | 'live';
sendMessage: (payload: FormattedSubmission) => Promise<{ messageId?: string; status: 'sent' | 'delivered' }>;
subscribe?: (
onIncomingMessage: (message: IncomingMessage) => void,
context?: { sessionId: string },
) => () => void; // returns "stop listening"
}
interface FormattedSubmission {
name: string; subject: string; message: string;
selectedAgent?: { id: string; name: string; role?: string };
pageContext?: { title?: string; url?: string; referrer?: string };
utm: Partial<Record<'utm_source' | 'utm_medium' | 'utm_campaign' | 'utm_term' | 'utm_content', string>>;
timestamp: number; // ms since the epoch
sessionId?: string; // live chat: identifies the conversation
}
interface IncomingMessage {
id: string; // used to ignore duplicates
text: string;
sender: 'agent' | 'system'; // 'system' is shown as a quiet, dashed note
timestamp: number;
}How the widget uses it:
-
sendMessageis called once for the first message (with the form details) and once for every message after that. For follow-ups,name,subject,selectedAgentandsessionIdare carried over, andmessageis the new text. Resolve to mark the message Sent (or Delivered). Reject to mark it Not sent. The visitor can retry. -
subscribeis called once when a conversation starts or is restored. CallonIncomingMessagefor each reply. Return a function that stops listening: it runs when the widget unmounts or the conversation ends. - Duplicate message ids are ignored, so it is safe to re-deliver.
- The widget keeps the latest
transportyou pass, so changing it between renders will not restart the conversation. Even so, creating the adapter outside the component is the clearer pattern.
const transport: WhatsAppTransportAdapter = {
mode: 'live',
async sendMessage(payload) {
const res = await fetch('/api/chat/send', { method: 'POST', body: JSON.stringify(payload) });
if (!res.ok) throw new Error('send failed');
return { status: 'sent' };
},
subscribe(onIncoming, context) {
const socket = new WebSocket(`wss://chat.example.com?session=${context?.sessionId}`);
socket.onmessage = (event) => onIncoming(JSON.parse(event.data)); // { id, text, sender, timestamp }
return () => socket.close();
},
};A ready-made adapter for any HTTP endpoint: n8n, Make, Zapier, or a proxy in front of the WhatsApp Cloud API. Import it from the adapters subpath so it stays out of your bundle unless used (about 0.7 kB gzipped).
import { createWebhookTransport } from 'whatsapp-chat-widget-react/adapters';
createWebhookTransport({
sendUrl: 'https://example.com/chat/send', // required
pollUrl: 'https://example.com/chat/replies', // optional: without it, no replies are received
pollIntervalMs: 3000, // optional, default 3000
headers: { Authorization: 'Bearer <token>' }, // optional, sent on every request
});Sending. POST sendUrl with Content-Type: application/json and the FormattedSubmission as the body. Reply with a 2xx status. Any other status counts as a failure and the visitor sees Not sent. The body is optional; if you return JSON, these fields are read:
{ "messageId": "wamid.123", "status": "delivered" }id is accepted in place of messageId. status is sent unless you return delivered.
Receiving. If you set pollUrl, the widget polls it with GET:
GET <pollUrl>?since=<ms>&session=<sessionId>
-
sinceis the largesttimestampit has seen so far (0at first). Return only messages newer than that. -
sessionis the conversation id. Return only that conversation's messages. - Respond with a JSON array, or
{ "messages": [...] }, of{ "id": "...", "text": "...", "sender": "agent", "timestamp": 1790000001000 }.senderandtimestampare optional (agentand the current time by default). - Polling pauses while the browser tab is hidden and resumes when it is visible. A failed poll is ignored and retried on the next tick.
The headers you set are visible to every visitor. They are useful for a rate-limiting token or routing hint, but they are not secret.
When the visitor submits the first message, in this order:
-
onSendis called. -
webhookUrlreceives the lead (see Lead Webhooks). -
onBeforeHandoffruns (up to 1.5 seconds). - The conversation starts and
sendMessagedelivers the first message.
If you use AI routing, it runs before all of that and can pick the agent and refine the first message. Follow-up messages only go through sendMessage: they do not trigger the webhook or onSend again.
The conversation is stored in the browser's sessionStorage under wcr:session:<widgetId>:
- It survives a reload and in-site navigation, and it is cleared when the tab is closed, or when the visitor chooses End chat.
- Messages that were still Sending… when the page unloaded are shown as Not sent, so the visitor can retry.
- Different widgets on the same site need different
widgetIdvalues, or they will share one conversation. - If storage is blocked or full, chat still works. It just will not survive a reload.
- Nothing is stored unless you enable live chat, and nothing leaves the browser except through your adapter.
The header link opens wa.me to the selected agent's number (or phoneNumber) with the transcript as the message, for example:
Name: Ada
Subject: Booking
You: Is the studio open on Saturday?
Agent: Yes, 10am to 4pm.
Failed messages and system notes are left out. If your messageTemplate is set, it formats the message. Change the speaker names with the you and agent labels.
- The offline notice and
allowOfflineMessages: falseapply to the pre-chat form, as before. - With
agents, the conversation is attached to the agent chosen on the form (or by AI routing), and every payload carriesselectedAgent.
These labels keys are used by live chat: conversation, composer, send, sending, sent, delivered, sendFailed, retry, continueOnWhatsApp, endChat, you, agent. See Right-to-Left and Translations.
- The thread is a
role="log"region named "Conversation" witharia-live="polite": new replies are announced without interrupting the visitor. It is focusable, so keyboard users can scroll it. - The composer has a visually hidden label, and Enter sends only when no text composition (IME) is in progress.
- Delivery state is text, never only a color.
- The test suite runs axe-core against the live view.
-
Messages stay "Not sent". Open the network tab. A CORS error means your
sendUrlmust allowPOSTwithContent-Type: application/jsonfrom your site's origin. A non-2xx response also counts as failure. -
Replies never arrive. Check that
pollUrlis set, that it returns the array format above, that every message has a uniqueid, and that you filter bysinceandsession. Polling pauses while the tab is hidden. -
Old conversation reappears. It is restored from
sessionStorage. Use End chat, or give the widget a newwidgetId. -
Two widgets share a conversation. Give each a different
widgetId. -
Replies appear twice. Make sure each message keeps the same
idevery time you return it. -
No "Continue on WhatsApp app" link. There is no valid phone number: set
phoneNumberor give your agents numbers.
See Backend Recipes for an end-to-end n8n and WhatsApp Cloud API setup.