A message card is an optional structured sidecar on a chat message: an image, title, description and one link that render as a richer bubble than plain text. Typical uses are "chat about this product" and "here is your order". The contract is open-vocabulary, so a host adds its own kinds without a package change, and the ready-made generic renderer covers most of them.
This guide is the host-facing recipe: how to map your data into the envelope, when to write a custom renderer, how to send, and the rules that keep cards predictable across React/Next.js, Vue, the plain-HTML widget and the headless SDK. The wire schema, validation limits and API behaviour are canonical in the API reference; the runtime behaviour is summarized in the frontend reference.
The envelope#
Every card is this shape (MessageCard in the SDK):
| Field | Required | Meaning |
|---|---|---|
type | yes | Open string kind, e.g. product or order; selects a host renderer |
version | yes | Envelope version, 1. Reserved for future schema changes |
title | yes | One-line human summary; also the fallback body for card-only sends |
description | no | Short supporting line (price, spec, status text) |
image_url | no | Absolute HTTPS image URL |
action | no | One {label, url} link, url absolute HTTPS |
data | no | Small JSON object (≤20 keys) your host renderer reads |
ref | no | Opaque host identity, e.g. product:42, used for client-side dedupe |
The card travels beside body, never instead of it. body stays the required plaintext summary that every consumer can render, including clients that never render cards. When you send a card with an empty draft, the SDK uses the card title as the body automatically, so a card-only send is still readable as text. Server validation, size caps and unknown-key stripping are described in the API reference.
Add a card kind: the mapping recipe#
You add a kind by mapping your existing model into the envelope; you usually do not touch the packages. The generic renderer already draws image, title, description and the HTTPS action (image stacked above the body on narrow screens, side-by-side at the md breakpoint and up, with the image sized as a thumbnail to keep the layout compact at every width), so a kind that fits that layout needs no renderer code at all.
- Pick a short stable
type(lowercase, no spaces), e.g.product. - Map the human-facing model fields to
title,descriptionandimage_url. - Map the destination page to
action: {label, url}if a link helps. - Put the machine-readable identity/status your renderer needs in
data. - Set
refto a stable per-entity key so repeat clicks do not double-stage.
Worked example: product#
A product page "Ask about this product" button builds this card. The generic renderer displays it as-is; no host renderer is required.
import { type MessageCard } from "@alzaf-it/chat-sdk";
export function productCard(product: {
id: string;
name: string;
summary: string;
price: string;
imageUrl: string;
pageUrl: string;
}): MessageCard {
return {
type: "product",
version: 1,
title: product.name,
description: `${product.price} · ${product.summary}`,
image_url: product.imageUrl, // absolute HTTPS
action: { label: "View product", url: product.pageUrl }, // absolute HTTPS
data: { product_id: product.id },
ref: `product:${product.id}`
};
}Mapping summary: product name → title, price/spec → description, primary image → image_url, product page → action.url, product id → data.product_id and ref.
Worked example: order#
An order snapshot maps status into data so a host renderer can draw a status chip; without that renderer the generic card still works.
export function orderCard(order: {
id: string;
statusLabel: string;
itemCount: number;
total: string;
detailUrl: string;
}): MessageCard {
return {
type: "order",
version: 1,
title: `Order #${order.id} — ${order.statusLabel}`,
description: `${order.itemCount} items · ${order.total}`,
action: { label: "Track order", url: order.detailUrl },
data: { order_id: order.id, status: order.statusLabel },
ref: `order:${order.id}`
};
}Keep data small and JSON-serializable. The server stores it but does not interpret it; only your renderer (or the generic layout, which ignores it) reads it. Never put secrets, tokens or personal data in a card.
When to write a custom renderer#
Write a renderer only when the generic image/title/description/action layout is not enough, for example a status chip, a badge row or a multi-column total. The built-in card remains the fallback for every unregistered type, so you can add renderers incrementally.
The registry is a Record<type, (card: MessageCard) => ReactNode> and is currently React-only. Pass it to ChatProvider to share it with the panel and popover, or directly to ChatPanel to override for one surface:
import { ChatProvider, ChatPanel, type CardRenderers } from "@alzaf-it/chat-react";
const cardRenderers: CardRenderers = {
order: (card) => (
<div className="flex flex-col gap-2 rounded-lg border border-border bg-card p-2.5 text-card-foreground">
<span className="w-fit rounded-full bg-secondary px-2 py-0.5 text-xs font-medium text-secondary-foreground">
{String(card.data?.status ?? "order")}
</span>
<span className="text-sm font-semibold">{card.title}</span>
{card.description ? (
<span className="text-xs text-muted-foreground">{card.description}</span>
) : null}
</div>
)
};
<ChatProvider client={client} cardRenderers={cardRenderers}>
<ChatPanel />
</ChatProvider>Renderer rules:
- Treat every string as untrusted text; render it as text, never as HTML.
- Do not assume
datais present or has your keys; guard with defaults. - A renderer that paints its own background must also set its own text color. The enclosing bubble can use a contrasting color (for example the viewer's own primary bubble uses
text-primary-foreground), so an inherited text color can be invisible; pairbg-cardwithtext-card-foregroundandbg-secondarywithtext-secondary-foreground. - For the normalized, trimmed fields and the HTTPS-only action, use the shared
cardView(card)helper rather than reading raw URLs. - Returning
nullis allowed; the message body still renders.
React also re-exports cardBodyText(card, body) for the title-dedupe rule and MessageCardView for the generic card. Vue and the plain-HTML widget render the generic card from the same shared cardView view-model with their own DOM and have no in-thread renderer registry; if you need custom chrome there, build it yourself around cardView from @alzaf-it/chat-sdk.
Send flows#
All three flows end in the same POST /conversations/{id}/messages with a card field; they differ only in how much UI you own.
Product-page "chat about this" → suggestCard#
The one-call host flow: open (or create) the customer's thread with that provider and stage the card as a removable suggestion. It refreshes the inbox if needed, prefers a non-resolved conversation with that provider, and skips staging when the same ref is already staged or present in the loaded window.
const { session, setOpen } = useChat();
async function askAboutProduct(product: Product) {
const { staged } = await session.suggestCard("shop-1", productCard(product), {
subject: "Product enquiry"
});
setOpen(true); // reveal the thread; user reviews and sends
return staged; // false when this ref was already staged/recent
}Staged suggestion → review → send#
suggestCard (or stageCard(card)) puts one card in state.stagedCard. The ready-made composer renders a thumbnail block with a Send now button, a remove button, and the hint "Send now, or add a message below to send it along.": Send now sends the card immediately — with whatever is typed in the box, or the card alone when the box is empty — while the main composer Send button sends the card together with the draft. The next session.send(body) attaches the staged card, keeps it if the send fails, and clears the slot only for the send that consumed it.
session.stageCard(productCard(product)); // stage manually
// ...user reviews and edits the draft...
await session.send("Is this still in stock?"); // card rides along
await session.send(""); // card-only send (uses the card title)
session.clearStagedCard(); // or drop it without sendingstate.stagedCard is a single slot, cleared when the user switches threads or returns to the inbox. Only one card is staged at a time (carousels/multiple actions are out of scope for now).
Direct sendMessage for non-UI callers#
Server-side jobs, bots or custom interfaces send the card directly:
import { createMessageId } from "@alzaf-it/chat-sdk";
await client.sendMessage(
conversationId,
"Your order is out for delivery.", // body is required
createMessageId(),
orderCard(order)
);Reuse the same client_message_id and the same card when retrying; the server compares the card alongside the body, so a reused id with a different card returns HTTP 409. The API reference documents the full DTO.
Rules and gotchas#
- A sent card is a point-in-time snapshot. It is stored with the message and is not updated when the product price or order status changes. Link out via
action.urlfor live data, or send a new card; do not treatrefas live state. - `ref` dedupes restaging only.
suggestCardcompares against the staged slot and the loaded message window (hasRecentCard). It is not a server uniqueness rule and does not update an existing message. - URLs must be absolute HTTPS.
image_urlandaction.urlare rejected by the server when non-HTTPS, and every client drops a non-HTTPS action. Relative paths do not work; use an absolute asset/CDN URL. - Unknown or malformed payloads degrade to plaintext. An unregistered
typeuses the generic card; a payload missingtypeortitlerenders thebodytext instead. Always setbody(or rely on the card-only title fallback) so nothing essential lives only in the card. - All card strings are plain text. Never inject HTML; the React renderer, Vue and the widget all render strings as text.
- Custom renderers are React-only. Vue and the widget always use the generic card layout; see the Vue and plain-HTML guides.
- Cards never change permissions. The server authorizes the conversation and the send; card content is display data and is never an authorization input.
Card carousels, multiple actions and executable (non-link) actions are not part of the card contract and stay deferred. File attachments are supported on messages but are not a card field: they are a sibling part of the message envelope. A card and one or more attachments can ride the same send, and a card-only, attachment-only or card-plus-text message is valid.
Runnable demo#
examples/nextjs-app includes a self-contained product page demo at /chat-preview. It renders a product with a real Ask about this product button. Clicking it calls session.suggestCard(...) against the preview's provider-conversation fixture, opens the shared thread, and stages the product card in the composer for review and send. The same page registers the order renderer above, so the preview's order card shows the host status chip while the product card renders through the built-in generic layout. The demo runs with the example app's mock client, so no backend is required:
pnpm build:packages
pnpm --filter @alzaf/nextjs-demo dev
# open http://localhost:3000/chat-previewFor a real integration, replace the mock client with your authenticated ChatClient and keep the flow: map your model to a card, call suggestCard, let the user review, then send. A host needs no renderer code for kinds that fit the generic layout.