Skip to content

Live Chat

Mcdavid Obioha edited this page Dec 2, 2026 · 1 revision

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={...}

Quick start

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" />;
}

What the visitor sees

  1. The usual pre-chat form (name, subject, message, agent picker, AI helpers).
  2. On submit, the panel changes into a conversation. Their first message is already in the thread.
  3. A scrollable thread, and a composer at the bottom. Enter sends. Shift+Enter adds a new line.
  4. Each message they send shows its state: Sending…, Sent, Delivered, or Not sent with a Retry link.
  5. Replies from your side appear on the left as they arrive.
  6. 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).

Props

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.

The adapter contract

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:

  • sendMessage is called once for the first message (with the form details) and once for every message after that. For follow-ups, name, subject, selectedAgent and sessionId are carried over, and message is the new text. Resolve to mark the message Sent (or Delivered). Reject to mark it Not sent. The visitor can retry.
  • subscribe is called once when a conversation starts or is restored. Call onIncomingMessage for 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 transport you pass, so changing it between renders will not restart the conversation. Even so, creating the adapter outside the component is the clearer pattern.

A WebSocket adapter

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();
  },
};

createWebhookTransport

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>
  • since is the largest timestamp it has seen so far (0 at first). Return only messages newer than that.
  • session is the conversation id. Return only that conversation's messages.
  • Respond with a JSON array, or { "messages": [...] }, of { "id": "...", "text": "...", "sender": "agent", "timestamp": 1790000001000 }. sender and timestamp are optional (agent and 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.

What else runs at the start of a live chat

When the visitor submits the first message, in this order:

  1. onSend is called.
  2. webhookUrl receives the lead (see Lead Webhooks).
  3. onBeforeHandoff runs (up to 1.5 seconds).
  4. The conversation starts and sendMessage delivers 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.

Persistence

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 widgetId values, 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.

Continue on WhatsApp

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.

Business hours and agents

  • The offline notice and allowOfflineMessages: false apply 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 carries selectedAgent.

Text and translations

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.

Accessibility

  • The thread is a role="log" region named "Conversation" with aria-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.

Troubleshooting

  • Messages stay "Not sent". Open the network tab. A CORS error means your sendUrl must allow POST with Content-Type: application/json from your site's origin. A non-2xx response also counts as failure.
  • Replies never arrive. Check that pollUrl is set, that it returns the array format above, that every message has a unique id, and that you filter by since and session. Polling pauses while the tab is hidden.
  • Old conversation reappears. It is restored from sessionStorage. Use End chat, or give the widget a new widgetId.
  • Two widgets share a conversation. Give each a different widgetId.
  • Replies appear twice. Make sure each message keeps the same id every time you return it.
  • No "Continue on WhatsApp app" link. There is no valid phone number: set phoneNumber or give your agents numbers.

See Backend Recipes for an end-to-end n8n and WhatsApp Cloud API setup.

Clone this wiki locally