The chat inside your page (React)
@boldare/askdare/react renders the chat in a page of your own Next.js app, as React components instead of an iframe. You get the widget's look ready to place, or hooks and primitives to write your own markup (ADR-0011). Streaming, limits and security stay in the library either way.
| You want | Use |
|---|---|
| A chat button on any site, also sites that aren't yours | The script-tag widget (Embedding) |
| The chat as part of a page of your Next.js app | DefaultChat, below |
| Your own markup and CSS | The primitives |
| To change the default components themselves | add ui |
Before you start:
- It needs React 19 and the same app that serves the chat route. The chat talks only to its own origin: it can't be used from another site. For that, use the widget.
- A chat inside a page is as safe as the page. Scripts on the page can read the conversation and the visitor's session, which the widget's iframe keeps from them. On pages that run scripts you don't trust (ads, tag managers with third-party tags), keep the widget.
Set up
You need the chat route from Getting started. Then:
1. Read the bot's public configuration in a Server Component and render the chat with it:
// app/help/page.tsx
import { getChatConfig } from '@boldare/askdare/next';
import { DefaultChat, Root } from '@boldare/askdare/react';
import { bots } from '@/askdare.config';
export default function HelpPage() {
const config = getChatConfig({ bots, bot: 'support' });
return (
<Root config={config}>
<DefaultChat className="help-chat" />
</Root>
);
}2. Give the chat a height. It fills the element it is in:
.help-chat { height: 640px; }That is all: the components are client components already, and the chat loads its stylesheets from the chat route, so there is no CSS to import and nothing to configure in your bundler.
getChatConfig(options) returns only what browsers may see: texts, the theme's name and the URLs of the stylesheets. Never the model, instructions, tools or keys.
| Option | Default | Meaning |
|---|---|---|
bots | required | The same bots as in createChatHandler. |
bot | required | The ID of the bot to show. |
basePath | /api/chat | The path of the chat route, if you changed it in createChatHandler. |
locale | en | The page's language, for a bot with locale: 'auto'. A bot with a fixed locale keeps it. |
Root
Root runs one bot's chat for the components inside it. It renders no element of its own.
| Prop | Meaning |
|---|---|
config | From getChatConfig. A different bot, route or language starts another chat. |
identity | The signed-in visitor: a token from your backend, as for askdare('identify'). See below. |
greeting, starters | This page's greeting and up to 4 suggested questions, instead of the bot's. |
context | A short description of the page for the assistant, up to 1,000 characters. Only for a bot with pageContext: true. |
onEvent | Called with what happens in the chat, such as a message sent or an answer rated, for analytics. Metadata only. A new function doesn't restart the chat. See Chat events. |
toolRenderers | Your components for tools' results, by tool name. DefaultChat and ToolResults draw them under the answer. See Tool cards. |
greeting, starters and context are the same as in askdare('configure') and are checked the same way (Styling).
Signed-in visitors
Pass the identity token your backend signs (Signed-in visitors):
<Root config={config} identity={token}>- To sign a visitor out, pass
identity={null}. Leaving the prop out, or passingundefined, keeps whoever is signed in. In a single-page app, aRootthat stays mounted across a sign-out must getnull. - A page that renders a token must not be cached. The token is in the page's HTML, so render the page per request (for example by reading
cookies()), and never serve it from a shared cache.
DefaultChat
The widget's look: header, conversation, message field, attachments, dictation and ratings, as the bot is configured.
| Prop | Default | Meaning |
|---|---|---|
className | On the element that holds the chat. Give it a height. | |
headingLevel | 2 | The level of the chat's title; the welcome heading is one below. Pick what fits your page's outline. |
colorScheme | the bot's | 'light', 'dark' or 'auto', for example to follow your site's dark mode switch. |
onClose | Shows a close button. Escape, pressed in the chat, calls it too. | |
components | Replaces Header, Welcome, Message or Footer. |
A replacement takes no props. It reads what it needs with the hooks:
'use client';
import { DefaultChat, useChat } from '@boldare/askdare/react';
function Header() {
const { bot, state, actions } = useChat();
return (
<header>
<h2>{bot.title}</h2>
{state.messages.length > 0 && (
<button type="button" onClick={() => void actions.newConversation()}>Start over</button>
)}
</header>
);
}
export function HelpChat() {
return <DefaultChat className="help-chat" components={{ Header }} />;
}The chat doesn't take focus or scroll to itself when the page loads. When an answer or a transcript arrives, it returns focus to the message field only if focus was in the chat or nowhere, never from your page's own fields, and without scrolling. actions.focus() always moves it. Escape pressed outside the chat is left to your page.
Your own markup
Every primitive renders one element with its usual data-ask-part name (Styling), and passes className, ref and other native props through. Write import * as Chat to keep them together:
'use client';
import * as Chat from '@boldare/askdare/react';
function Bubble() {
const message = Chat.useMessage();
return (
<Chat.Message className={message.role === 'user' ? 'mine' : 'theirs'}>
<Chat.MessageText />
<Chat.ToolApproval />
<Chat.ToolResults />
<Chat.MessageFiles />
<Chat.Citations />
<Chat.HandoffStatus />
{message.forms?.map((form) => (
<Chat.Form key={form.callId} form={form} />
))}
<Chat.FeedbackButton rating="up">👍</Chat.FeedbackButton>
<Chat.FeedbackButton rating="down">👎</Chat.FeedbackButton>
<Chat.QuickReplies />
</Chat.Message>
);
}
export function PlainChat({ config }: { config: Chat.ChatConfig }) {
return (
<Chat.Root config={config}>
<Chat.Panel className="plain-chat">
<Chat.HandoffButton />
<Chat.Messages>
<Chat.LoadEarlier />
<Chat.MessageList>
<Bubble />
</Chat.MessageList>
<Chat.Status />
</Chat.Messages>
<Chat.ErrorMessage />
<Chat.Composer>
<Chat.Files />
<Chat.AttachButton>Attach</Chat.AttachButton>
<Chat.Input />
<Chat.DictateButton>Dictate</Chat.DictateButton>
<Chat.Recorder />
<Chat.Send>Send</Chat.Send>
</Chat.Composer>
<Chat.Disclosure />
</Chat.Panel>
</Chat.Root>
);
}Without Theme and DefaultChat, no stylesheet of the chat loads: the look is all yours.
Keep the AI notice. Visitors must be told they are talking to an AI (EU AI Act, art. 50; see Compliance). DefaultChat shows it under the message field. In your own markup, place Disclosure. In development, Root notes once in the console when the chat rendered without one. Set widget.disclosure: false in defineBot when your page already tells visitors; that hides Disclosure and silences the note.
| Primitive | Element | What it does |
|---|---|---|
Theme | div | Sets the bot's tokens (--ask-*) and theme variants for everything inside, and loads the theme and its fonts. Takes colorScheme. |
Panel | section | The chat's frame, a region named after the bot. Files dropped on it are attached. |
Messages | div | The conversation, a log that follows the latest message. Next to it, a visually hidden status (data-ask-part="announcement") announces each finished answer once to screen readers. When older messages load above, it keeps what the visitor was reading in place and announces them. |
LoadEarlier | button | Loads the older messages of a long conversation, a page at a time, at the top of Messages. It shows while there are any (state.earlier) and also loads them when the visitor scrolls up to it. While a page loads it says so, keeps focus and has aria-disabled and data-loading. Focus stays on it, in view, with the older messages under it; when the start is reached and it goes away, the oldest message takes focus. Children replace its label. See Long conversations. |
MessageList | none | Renders its children once per message. |
Message | div | One message, with data-role and data-status. |
MessageText | div | The text: the visitor's as typed, an answer as Markdown, typing dots before the first word. |
Markdown | none | Renders a text as the chat renders answers. |
Citations | ol | The answer's sources. |
ToolApproval | div | A tool call the answer asks the visitor to approve (tool-approval, data-state), a group labelled by the call's summary, with Approve (approve) and Decline (decline). See Approving a tool call. |
ToolResults | div | The answer's tool cards (tool-result, with data-ask-tool), each drawn by the component Root's toolRenderers has for its tool, in call order. See Tool cards. |
Link | a or span | A link for a URL from a tool's payload, checked as links in answers are: only https, http and mailto, opened in a new tab. Any other URL renders the text alone. |
MessageFiles | ul or p | The files sent with a message. |
HandoffButton | button | "Talk to a person" (handoff.button; children replace it): asks for a person for the latest answer. Renders nothing for a bot without handoff or with button: false, and before the first answer. While a turn runs or a handoff is under way it has aria-disabled, so it keeps focus. See Handoff and forms. |
HandoffStatus | p | Where a handoff for this answer stands, as plain text (data-state): "Connecting you…", then its outcome. A polite status. Renders nothing when the handoff has a form, which says it instead. |
Form | form | One of the answer's forms (useMessage().forms), drawn from its description in the bot's configuration. See Handoff and forms. |
FeedbackButton | button | Rates the answer; takes rating="up" or "down". See Answer ratings. |
QuickReplies | div | The options the latest answer offers, as a group of buttons (reply) that show their text as plain text. A click sends the option as the visitor's message. Inside MessageList it renders under the latest answer only; placed anywhere else, such as above the Composer, it shows the latest answer's options there. Either way they go away once the visitor sends anything. The default look follows the theme's replies variant (Themes). See Reply options. |
Composer | form | Submitting it sends the draft, Enter in the Input included. An onSubmit of yours that calls event.preventDefault() takes the message over. |
Input | textarea | The message field: Enter sends, Shift+Enter starts a new line, pasted files are attached. Your onKeyDown or onPaste can prevent either. |
Send | button | Sends; disabled until there is something to send. |
AttachButton | button | Opens the file picker. Renders nothing when the bot takes no attachments. |
Files | ul | The files picked for the next message. |
DictateButton | button | Starts a dictation. Renders nothing without voice input. |
Recorder | div | The running dictation, with cancel and done. Renders nothing otherwise. |
Status | p | What the assistant is doing before it writes, or that a conversation is loading. |
ErrorMessage | p | The latest problem, in the visitor's language. |
HumanCheck | div | The Cloudflare Turnstile challenge, while a new session waits for it. Renders nothing for a bot without security.humanVerifier; a chat whose bot has one must render it (Configuration). |
Disclosure | p | The AI notice (disclosure.text), with a link to widget.disclosure.privacyUrl when the bot has one. Children replace the text with your own wording. Renders nothing with disclosure: false. |
Primitives that have nothing to show render nothing, so you can place them without conditions.
Never render an answer as HTML. Model output can be steered by whatever the model reads. MessageText and Markdown turn it into elements without ever producing HTML, allow only http, https and mailto links, and never load images. If you render message.text yourself, render it as text.
Tool cards
A tool can pick what the visitor may see of its result with ui (Tools). Give Root a component for it, and the chat draws it under the answer, live and after a reload:
'use client';
import * as Chat from '@boldare/askdare/react';
// Types only: the tool runs on the server and never reaches this bundle.
import type { findSlots } from '@/tools';
function SlotList({ data }: Chat.ToolRendererProps<typeof findSlots>) {
const { actions } = Chat.useChat();
return (
<ul className="slots">
{data.slots.map((slot) => (
<li key={slot}>
<button type="button" onClick={() => void actions.send(`Book ${slot}`)}>
{slot}
</button>
</li>
))}
</ul>
);
}
const toolRenderers = { find_slots: SlotList } satisfies Chat.ToolRenderers<[typeof findSlots]>;
export function Help({ config }: { config: Chat.ChatConfig }) {
return (
<Chat.Root config={config} toolRenderers={toolRenderers}>
<Chat.DefaultChat className="help-chat" />
</Chat.Root>
);
}- A component gets
{ data, name, callId }.datais what the tool'suireturned, typed from the tool withToolRendererProps<typeof tool>.satisfies ToolRenderers<[…]>checks each component against its tool's payload and the tool names;Rootalso takes a plain map without types. Everything else comes from the hooks. - Render
dataas text. React escapes it. Never pass it todangerouslySetInnerHTML, and put URLs from it inChat.Link, which dropsjavascript:and every other scheme buthttps,httpandmailto. Load images only from URLs your tool builds itself, never from the model's arguments: an image URL can carry data out if a prompt injection steers the model. - To act, send a message.
actions.send(text)sends the visitor's own words, exactly as if they had typed them; the model decides what happens, as always. A card can't run a tool or anything else by itself. - No component, no card. A tool without one shows nothing (the answer's text still tells the result), and the console says so once per tool. If a component throws, its card is left out and the chat goes on.
- Placement.
DefaultChatputs the cards under the answer's text. In your own markup, placeToolResultsinsideMessageList; style the cards yourself, with the chat's tokens (var(--ask-color-border)and the others) so they follow the theme. - The script-tag widget draws them too, for a bot that shows your own page in its iframe: render that page with
EmbedRootfrom@boldare/askdare/embedand the sametoolRenderers. See Embedding: your own page in the iframe.
Handoff and forms
A bot with handoff lets visitors ask for a person, and a bot with forms can show a form under an answer (ADR-0030, ADR-0031). DefaultChat puts "Talk to a person" in its header and the forms and the handoff's status under the answer. In your own markup, place HandoffButton where visitors look for help, and HandoffStatus and one Form per form inside MessageList, as in the example above.
Formrenders aformnamed by its title, then aform-fieldper field with a visiblelabel. Optional fields say so (form.optional). Aselectstarts withform.choose; aconsentfield is a checkbox, followed by a link to the bot's privacy policy whenwidget.disclosurehas one. Every text is plain text. Email and phone fields tell the browser what to fill in (autocomplete), and so do fields namedname,companyandorganization.- Errors. Sending checks the values by hand first, as the server does (required, email, phone, length, option), then the server checks them again. Each error is a
form-errortied to its field witharia-describedby, the field hasaria-invalid, and the first field with an error gets focus. Typing into a field clears its error. A failure of the whole form, such as a lost connection, is aform-errorwithrole="alert", and the values stay to try again. - Once sent, the form becomes its
form-donetext, astatus: the form'sdone(orform.done), or for a handoff's form the handoff's outcome, which names the email address the visitor gave (handoff.sentTo). A form whose handle is no longer valid says so (form.expired). If the visitor had just sent it, focus moves to that text, since the button it was on is gone. - Purposes.
form.purposeislead,handoff(contact details for a person) ormessage(a message left while nobody is available, titledhandoff.unavailableTitle).data-purposeon theformhas it, anddata-ask-formthe form's name. - Parts:
handoff(the button),handoff-status(withdata-state),form,form-title,form-field(withdata-type),form-optional,form-error,form-submit(witharia-disabledwhile it sends) andform-done(withdata-state). - Your own form.
useChat()has everythingFormuses: the forms under each message (message.forms:callId,name,purpose,state,handle, and the server'serrorsby field as text keys), their descriptions inbot.forms, andactions.submitForm(handle, values). Look the error keys up witht; a key your chat doesn't know is a generic error (error.form.invalid).
function Callback() {
const message = Chat.useMessage();
const { bot, actions, t } = Chat.useChat();
const form = message.forms?.find((item) => item.name === 'callback');
if (form?.state === 'sent') return <p role="status">{t('form.done')}</p>;
if (form?.state === 'expired') return <p>{t('form.expired')}</p>;
const handle = form?.handle;
if (!form || !handle) return null;
const { title } = bot.forms.find((item) => item.name === form.name) ?? {};
return (
<form
onSubmit={(event) => {
event.preventDefault();
const phone = String(new FormData(event.currentTarget).get('phone') ?? '');
void actions.submitForm(handle, { phone });
}}
>
<label>
{title}
<input name="phone" type="tel" autoComplete="tel" />
</label>
{form.errors?.phone && <p>{t(form.errors.phone as 'error.form.phone')}</p>}
<button type="submit" aria-disabled={form.state === 'submitting'}>
{t('form.submit')}
</button>
</form>
);
}Approving a tool call
A tool with approval waits for the visitor before it runs (Tools, ADR-0038). The answer that asks carries message.approval, and DefaultChat shows it under the answer's text, in the script-tag widget too. In your own markup, place ToolApproval inside MessageList, as in the example above.
ToolApprovalrenders adivgroup (tool-approval, itsdata-statethe card's state) labelled by the summary, which shows as plain text in ap, then theapproveanddeclinebuttons (approval.approve,approval.decline). The buttons are disabled while a turn runs and once the card is answered; then astatusunder the summary says the outcome (approval.approved,approval.declined,approval.expired). Renders nothing on a message without a card.- States.
message.approval.stateispendinguntil the visitor answers,approvedordeclinedfrom the moment they do, andexpiredonce its 10 minutes passed, the visitor wrote a message instead, or the server no longer took the answer. A reload brings each card back in its state; apendingone with a freshhandle. - Answering starts the bot's next answer, as a message would, without a visitor message of its own.
- Your own card.
useChat()has everythingToolApprovaluses:message.approval(callId,nameof the tool,summary,state,handle) andactions.approve(handle, approve).
function Confirm() {
const { approval } = Chat.useMessage();
const { state, actions, t } = Chat.useChat();
if (!approval) return null;
const answer = (approve: boolean) => () => approval.handle && void actions.approve(approval.handle, approve);
return approval.state === 'pending' ? (
<p>
{approval.summary}{' '}
<button type="button" disabled={state.busy} onClick={answer(true)}>{t('approval.approve')}</button>
<button type="button" disabled={state.busy} onClick={answer(false)}>{t('approval.decline')}</button>
</p>
) : (
<p role="status">{approval.summary}: {t(`approval.${approval.state}`)}</p>
);
}Long conversations
A stored conversation comes back in pages of whole turns, the latest first (Protocol). The chat shows the latest page; state.earlier says whether older ones exist, and actions.loadEarlier() puts the page before above the messages. DefaultChat shows LoadEarlier at the top of the conversation, which loads as the visitor scrolls up and works as a button from the keyboard. In your own markup, place LoadEarlier first inside Messages, or call loadEarlier() from your own control:
function Earlier() {
const earlier = Chat.useChatState((state) => state.earlier);
const { actions } = Chat.useChat();
if (earlier === 'none') return null;
return (
// aria-disabled, not disabled: a disabled button would drop keyboard focus while it loads.
<button
type="button"
aria-disabled={earlier === 'loading'}
onClick={() => void actions.loadEarlier()}
>
Older messages
</button>
);
}Messages keeps the visitor's place when older messages go in above, whatever control loaded them. If a page fails to load, state.error says so and the same page can be tried again; if the conversation is gone, paging stops and the error says so. The server's cursor to older pages stays inside the chat; starting over or signing in drops it.
Hooks
useChat()returns{ state, actions, bot, t }and re-renders on every change.useChatState(select)returns one value and re-renders only when it changes:useChatState((state) => state.busy). Return a value from the state, not a new object.useMessage()returns the message being rendered, insideMessageList.useFrame()returns{ close }insideEmbedRoot, on your own page in the widget's iframe, andnulleverywhere else.closeasks the widget to close its panel (undefined for an inline chat). The default look, ejected or not, uses it to become the page's main landmark with a close button; your own markup can use it for its close button. See Embedding.
state | Meaning |
|---|---|
phase | 'starting' on the server and until the chat knows the visitor, 'loading' while a stored conversation loads, then 'ready'. |
busy | A turn is under way. |
messages | Each with id, role, text, status ('streaming', 'done', 'error'), citations, files, feedback, replies (the options the answer offers, plain text), handoff (the state of a handoff after this answer: 'requested', 'sent', 'saved', 'unavailable', 'failed' or 'limited'), forms (the forms under it, see Handoff and forms) and approval (a tool call it asks the visitor to approve, see Approving a tool call). |
earlier | Older messages of a stored conversation: 'more' (load them with loadEarlier()), 'loading', or 'none' once the start shows, or without a stored conversation. |
draft, files | The message field's text and the files picked for the next message. |
error, activity | The latest problem, and what the assistant is doing before it writes, or "Reconnecting…" (status.reconnecting) while an answer whose connection dropped resumes. |
dictation, elapsed, canDictate | The dictation: 'idle', 'recording' or 'transcribing', its seconds, and whether this browser can record. |
ratings, commenting | The visitor's ratings by message.feedback.key, and the answer the chat asks about after a 👎. |
actions | Meaning |
|---|---|
send(text?) | Sends the draft, or text on its own (a suggested question, or one of the latest answer's replies). |
setDraft(text) | Sets the message field. |
addFiles(files), removeFile(key) | Files for the next message. |
startDictation(), finishDictation(), cancelDictation() | Dictation; finishing puts the transcript into the draft. |
newConversation() | Deletes the conversation and starts with an empty chat. |
loadEarlier() | Loads the page of older messages before the oldest shown and puts it above, while earlier is 'more'. |
rate(messageId, rating, comment?), dismissComment() | Ratings: 'up', 'down', or null to take one back. |
handoff() | Asks for a person for the latest answer (the bot's handoff); its handoff is 'requested' until the outcome, or until its form is sent. |
submitForm(handle, values) | Sends a form's values, by field name: text, or true/false for a consent field. The form's state goes 'submitting', then 'sent', back to 'open' with errors or error, or 'expired'. |
approve(handle, approve) | Answers a pending approval card: true approves the call, false declines it. The card shows the answer at once, and the bot writes its next answer. Does nothing while a turn runs; a card the server no longer takes becomes 'expired'. |
focus() | Moves keyboard focus to the message field. |
bot holds the bot's public settings in the visitor's language (title, greeting, starters, placeholder, avatar, disclosure, what may be attached, and the descriptions of its forms). t(key) returns any of the chat's texts.
Styling
The same tokens and parts as the widget (Styling, Themes), with three differences inside a page:
- The theme root is an element, not the document.
Theme(insideDefaultChat) renders<div data-askdare-root data-ask-bot="support" …>with the variant attributes. Where the widget's docs say:rootor<html>, read that element. - Your site's CSS reaches the chat. The chat's styles are in
@layer askdareand never reach outside the chat. Your own unlayered CSS wins over them, on purpose:[data-ask-part="bubble"] { border-radius: 6px; }in your stylesheet just works. A broad rule of your site, such asbutton { text-transform: uppercase; }, applies to the chat's buttons too. - The bot's
widget.cssstill applies, scoped to that bot's chat.:rootin it means the theme root.
With a CSS reset (Tailwind)
A reset written without a layer overrides the chat's layered styles. Put the reset in a layer that comes before askdare:
/* Tailwind CSS 4 */
@layer theme, base, askdare, components, utilities;
@import "tailwindcss";/* Tailwind CSS 3 */
@layer tailwind-base, askdare;
@layer tailwind-base {
@tailwind base;
}
@tailwind components;
@tailwind utilities;With that order the chat looks the same as without the reset, and your utilities still win over it.
Content Security Policy
The widget brings its own policy inside the iframe. A chat inside your page lives under your page's policy, which must allow, all for your own origin:
| Directive | Why |
|---|---|
connect-src 'self' | The chat's requests to the chat route. |
style-src 'self' | The theme, skin and font stylesheets from the chat route. |
font-src 'self' | The built-in themes' fonts. |
img-src 'self' blob: data: | Previews of files the visitor attaches, and a data: avatar. |
Permissions-Policy: microphone=(self) | Dictation, if the bot has voice input. |
script-src https://challenges.cloudflare.com, frame-src https://challenges.cloudflare.com | The human check, if the bot has security.humanVerifier. DefaultChat shows it; a headless chat renders HumanCheck. |
Eject the default look
When the props and slots of DefaultChat aren't enough, copy its source into your app and change it:
npx @boldare/askdare add uiIt writes the components and their stylesheet to components/askdare and never overwrites a file (Command line). Then change one import:
- import { DefaultChat } from '@boldare/askdare/react';
+ import { DefaultChat } from '@/components/askdare';The copy imports only @boldare/askdare/react, so Root, the hooks and the primitives keep coming from the library and keep getting its fixes. The copied files are yours: when a later version changes the default look, the changelog says so, and you take what you want by hand.
Good to know
- Server rendering. The chat renders on the server in its starting state, with the greeting and suggestions, and connects after hydration. A stored conversation appears then.
- Several chats on a page work, each in its own
Root, also for different bots with different themes. - One conversation per bot and browser, shared by every page that shows that bot, and by the widget on the same origin.
- Switching the language. Call
getChatConfigwith the newlocaleand pass the result toRoot: the same chat switches to that language's texts, greeting and placeholder, and the conversation, the unsent message and an answer still streaming stay. Another bot orbasePathstarts another chat. Only a bot withlocale: 'auto'switches; see Texts. - Sizes (gzipped, in your bundle): about 32 KB for everything, about 10 KB when you use only
Rootand the hooks. The Markdown renderer is loaded only if you renderMessageTextorMarkdown.