Build a custom chat UI with the Reponly SDK

Build your own in-app support chat on the Reponly customer API with the reponly npm package: sessions, messages, files, real-time updates and live visitors. Needs the Pro plan.

Use this when the hosted widget doesn't fit your app and you want the chat in your own components. The reponly package is the TypeScript SDK the hosted widget itself runs on. It has no dependencies and is MIT licensed (source).

Before you start

  • A custom UI needs the Pro plan.
  • Add your site's origin to Allowed domains in the product's General tab, so no other site can use your chat. Once any domain is listed, calls from other origins fail with 403 origin_not_allowed; origins must match exactly, scheme and port included.
  • Copy the project key (pk_...) and the base URL from the product's Custom UI tab.

Install

npm install reponly

Example

import { getVisitorKey, ReponlyClient, watchPresence, watchTriggers } from "reponly";

// This browser's key on your site: links live visits to the chat (same key in both places).
const visitorKey = getVisitorKey("pk_your_project_key");
const chat = new ReponlyClient({ projectKey: "pk_your_project_key", baseUrl: "https://reponly.com", visitorKey });

// Live visitors (Pro): on every page, not only while the chat is open.
const presence = watchPresence({
  projectKey: "pk_your_project_key",
  baseUrl: "https://reponly.com",
  visitorKey,
  onPreview: (reply) => showReplyBubble(reply.senderName, reply.text), // an agent reply they haven't read
  canShowPreview: () => !chatIsOpen,
});
// When they dismiss that bubble or open the chat: presence.previewSeen();

await chat.connect(identityToken); // identityToken from your backend (see Identify users); leave it out for anonymous visitors

const config = await chat.getConfig(); // welcome text, triggers, askForEmail, attachments, paused

// Automatic messages (Pro): same rules as the hosted widget (page, delay, audience, once each).
const triggers = watchTriggers(config.triggers, {
  projectKey: "pk_your_project_key",
  onShow: (trigger) => showBubble(trigger.message), // a bubble by your chat button
  canShow: () => !chatIsOpen,
});
let openedFrom = null;
function onChatOpen() {
  // From the bubble or not: no more automatic messages after this.
  openedFrom = triggers.chatOpened(); // show openedFrom?.message on top instead of the welcome
  presence.previewSeen();
}

const off = chat.subscribe((event) => {
  // "message.created" | "message.updated" | "message.deleted" | "restriction.updated"
  // | "connection" (state "open" after every reconnect: refetch the conversation then)
});

try {
  // The current page, title, language and time zone go with it, so agents see where you were.
  // welcomeShown: you render config.appearance.welcomeText above the chat, so agents see it too.
  await chat.sendMessage("Hello!", {
    welcomeShown: Boolean(config.appearance.welcomeText),
    triggerId: openedFrom?.id, // only matters on the message that starts the conversation
  });
} catch (error) {
  if (error.isRateLimited || error.isRestricted) showNotice(error.message, error.retryAt);
}

// Files: upload first, then send the ids (a message may be files only).
const file = await chat.uploadAttachment(input.files[0]);
await chat.sendMessage("", { attachmentIds: [file.id] });

// Guests: after their first message, offer to email them the answer.
await chat.setContactEmail("[email protected]");

// While your chat is visible, report what was read: no email for replies they already saw.
await chat.markRead(conversationId, lastSeq);

Instructions for a coding agent

The full contract (endpoints, payloads, real-time events and error codes), written for Claude Code, Cursor or another coding agent. Paste it with your own project key in place of the example one:

Build our own in-app support chat UI on top of the Reponly customer API. Don't use the Reponly widget iframe.

Requirements:
1) Base URL: https://reponly.com. Project key: `pk_your_project_key` (public).
2) The workspace must be on Pro, or browser calls fail with 402 (plan_required). If the project lists "Allowed domains" in Reponly, our site's origin must be one of them (exact match, scheme and port included), or calls fail with 403 (origin_not_allowed). With none listed, any origin may call.
3) Start a session with `POST /api/v1/sessions` `{ projectKey, customerToken?, identityToken?, visitorKey? }` (`visitorKey`: see 7f). Store the returned `customerToken` (localStorage is fine) and send it back on later visits to resume the same customer.
4) For signed-in users, pass an `identityToken` from our backend (see Reponly's "Identify users" instructions: POST /api/v1/identify). The same user then gets the same chat on every device.
5) Every other call sends `Authorization: Bearer <customerToken>`.
6) Before rendering, fetch `GET /api/v1/projects/${projectKey}/config` for the welcome text, availability, `askForEmail`, `attachments`, `paused` and `triggers`. The session response says whether we already have the customer's email (`customer.hasEmail`).
7) Send with `POST /api/v1/messages` `{ content, clientMessageId, context, attachmentIds?, welcomeShown?, triggerId? }`. Generate `clientMessageId` once per message (e.g. `cm_` + random hex) and reuse it on retries, so a retry never sends twice. `context` is `{ pageUrl, pageTitle, language, timezone, screen }` from the current page (agents see it next to the message; secret-looking query values are redacted).
7a) Email fallback: when `askForEmail` is `after_first_message` and `hasEmail` is false, show an "Email me the answer" field after the customer's first message and save it with `POST /api/v1/contact` `{ email }`. When it is `before_first_message` (or `paused` is true), ask before the first message and send it as `contactEmail`. When the customer hasn't read an agent reply about 90 seconds later, Reponly emails it with a link back to the chat.
7b) Read receipts: while the chat is visible, call `POST /api/v1/conversations/{id}/read` `{ seq }` with the newest message seq. Without it, every reply is also emailed (when we have an address). For an unread badge, count agent messages with `seq` above the conversation's `customerLastReadSeq` (from the list in step 8); it is shared across devices, so don't keep your own copy.
7c) Files: if `attachments` is true, upload each file with `POST /api/v1/attachments` (multipart field `file`, up to 10 MB: images, PDFs, text/CSV, Office files, zip, mp4/mov/webm) and send up to 5 returned ids as `attachmentIds`. Render `message.attachments`: images (`kind: "image"`) inline, others as download links.
7d) Greeting: if the chat shows `appearance.welcomeText` above the messages, send `welcomeShown: true`. Reponly stores that text (looked up on its side) as the new conversation's greeting, so agents see what the customer was answering. Without it the agent's inbox starts at the customer's first message, with no context.
7e) Automatic messages (Pro): the config's `triggers` (`id`, `message`, `pathContains`, `delaySeconds`, `audience`) should appear as a bubble by our chat button, with the hosted widget's rules: after `delaySeconds` on a page whose path+query contains `pathContains` (case-insensitive; null = every page), re-checked on client-side navigation; `audience` "new" or "returning" by whether this browser visited before; each trigger at most once per visitor; never while the chat is open or once the visitor has ever opened it. Use the SDK's `watchTriggers` (below), which does exactly this. Clicking the bubble opens the chat with the trigger's message on top instead of the welcome text; send its `id` as `triggerId` with the message that starts the conversation, so it becomes the greeting agents see.
7f) Live visitors (Pro): on every page of our site, not only while the chat is open, report the visitor with the SDK's `watchPresence` (below). It posts `POST /api/v1/presence` `{ projectKey, visitorKey, pageUrl, pageTitle, referrer, timezone }` every 15 seconds while the tab is visible and on client-side navigation, and stops by itself when live visitors are off. Without it our visitors never appear on Reponly's Live page or as "Online now", and an agent who messages them from there is never seen. Use one `visitorKey` per browser (the SDK's `getVisitorKey`, kept in localStorage) and pass the same key to `ReponlyClient` (it goes with the session), so the visit and the chat are the same person. Each answer may carry `preview` (`messageId`, `text`, `senderName`, `senderAvatarUrl`): the newest agent reply they haven't read, e.g. one an agent sent before they ever opened the chat. Show it in a bubble by our closed chat button; clicking it opens the chat (which then holds that conversation). Call `previewSeen()` when the bubble is dismissed or the chat opens, so it doesn't come back.
8) History: `GET /api/v1/conversations` (newest first; each has `id`, `lastMessageAt`, `lastMessagePreview`, `messageSeq`, `customerLastReadSeq`), then `GET /api/v1/conversations/{id}/messages?after={seq}`. Messages are ordered by `seq`. `POST /api/v1/messages` resumes the customer's active conversation (or starts one) and returns its `conversationId`.
8a) Show who replied: agent messages carry `senderName` (first name) and `senderAvatarUrl` (their current photo, or null). Render a small round photo and the name next to each agent reply, and in the reply bubble from 7f; use the photo only when it's an `https://` URL, otherwise the name's initial.
9) Real-time: subscribe to the Pusher-protocol channel `private-{realtime.channelPrefix}customer.{customerId}`, using the `realtime` settings (key, wsHost, wsPort, forceTLS, channelPrefix) in the project config. Authorize via `POST /api/v1/realtime/auth` with the bearer token. Events: `message.created` (`{ message }`), `message.updated` (`{ message }`: an agent edited it, replace the message with that `id`), `message.deleted` (`{ conversationId, messageId }`: an agent deleted it, remove it) and `restriction.updated` (refetch `/api/v1/status`). A `message.created` can belong to another conversation than the one on screen (a new one, or one an agent started): switch to it. After every reconnect, refetch the whole conversation's messages and replace the list (keep the customer's own messages still sending), so edits and deletions missed meanwhile show up.
9b) Edited messages: when `editedAt` is set, show a small "edited" next to the time. An edit never plays a sound or counts as a new unread message.
9a) Sound: when a `message.created` from an agent arrives that isn't on screen yet (not history, not a resync or a redelivered event), play a short, soft sound, at most once per burst of messages. Browsers block audio until the visitor clicks or types, so create the audio after their first gesture and skip sounds before it. Put a mute toggle in the chat header (`aria-pressed`), remembered in localStorage.
10) `GET /api/v1/status` returns any restriction or cooldown. Disable the composer and show the retry time when present.
11) Errors share one envelope: `{ success: false, error: { code, message, retryAt } }`. Show `message` to the user. Handle `rate_limited` (429, `Retry-After`), `customer_restricted` (403), `email_required` (400) and `unauthorized` (401: start a new session).
12) Prefer the TypeScript SDK: `npm install reponly` (source and docs: https://github.com/reponly-com/reponly-js). `ReponlyClient` does sessions, token storage, expired-session recovery and real-time for you, so steps 3-9 are mostly handled. It does not retry failed sends: retry with the same `clientMessageId` (pass it in `sendMessage` options). Call `connect(identityToken)` before `subscribe()`; `subscribe()` reuses that session and emits `{ type: "connection", state: "open" }` after every (re)subscribe. Example:

import { getVisitorKey, ReponlyClient, watchPresence, watchTriggers } from "reponly";

// This browser's key on your site: links live visits to the chat (same key in both places).
const visitorKey = getVisitorKey("pk_your_project_key");
const chat = new ReponlyClient({ projectKey: "pk_your_project_key", baseUrl: "https://reponly.com", visitorKey });

// Live visitors (Pro): on every page, not only while the chat is open.
const presence = watchPresence({
  projectKey: "pk_your_project_key",
  baseUrl: "https://reponly.com",
  visitorKey,
  onPreview: (reply) => showReplyBubble(reply.senderName, reply.text), // an agent reply they haven't read
  canShowPreview: () => !chatIsOpen,
});
// When they dismiss that bubble or open the chat: presence.previewSeen();

await chat.connect(identityToken); // identityToken from your backend (see Identify users); leave it out for anonymous visitors

const config = await chat.getConfig(); // welcome text, triggers, askForEmail, attachments, paused

// Automatic messages (Pro): same rules as the hosted widget (page, delay, audience, once each).
const triggers = watchTriggers(config.triggers, {
  projectKey: "pk_your_project_key",
  onShow: (trigger) => showBubble(trigger.message), // a bubble by your chat button
  canShow: () => !chatIsOpen,
});
let openedFrom = null;
function onChatOpen() {
  // From the bubble or not: no more automatic messages after this.
  openedFrom = triggers.chatOpened(); // show openedFrom?.message on top instead of the welcome
  presence.previewSeen();
}

const off = chat.subscribe((event) => {
  // "message.created" | "message.updated" | "message.deleted" | "restriction.updated"
  // | "connection" (state "open" after every reconnect: refetch the conversation then)
});

try {
  // The current page, title, language and time zone go with it, so agents see where you were.
  // welcomeShown: you render config.appearance.welcomeText above the chat, so agents see it too.
  await chat.sendMessage("Hello!", {
    welcomeShown: Boolean(config.appearance.welcomeText),
    triggerId: openedFrom?.id, // only matters on the message that starts the conversation
  });
} catch (error) {
  if (error.isRateLimited || error.isRestricted) showNotice(error.message, error.retryAt);
}

// Files: upload first, then send the ids (a message may be files only).
const file = await chat.uploadAttachment(input.files[0]);
await chat.sendMessage("", { attachmentIds: [file.id] });

// Guests: after their first message, offer to email them the answer.
await chat.setContactEmail("[email protected]");

// While your chat is visible, report what was read: no email for replies they already saw.
await chat.markRead(conversationId, lastSeq);

13) Make it accessible: a labelled message list with `aria-live="polite"`, keyboard-only sending, visible focus.
14) Add tests for sending, retries (same clientMessageId), `welcomeShown`/`triggerId` on sends, automatic messages (shown once, not after the chat was opened), sound (new agent replies only, never when muted), live visitors (same `visitorKey` for presence and the session; agent reply bubble hidden while the chat is open and after it was seen), rate-limit display, edited and deleted agent messages (live and after a reconnect) and reconnect resync.

Every product in one inbox, at one flat price.

Create your inbox

Start with 14 days of Pro. No card required.