Skip to content
askdareDocumentation

    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 wantUse
    A chat button on any site, also sites that aren't yoursThe script-tag widget (Embedding)
    The chat as part of a page of your Next.js appDefaultChat, below
    Your own markup and CSSThe primitives
    To change the default components themselvesadd 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.

    OptionDefaultMeaning
    botsrequiredThe same bots as in createChatHandler.
    botrequiredThe ID of the bot to show.
    basePath/api/chatThe path of the chat route, if you changed it in createChatHandler.
    localeenThe 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.

    PropMeaning
    configFrom getChatConfig. A different bot, route or language starts another chat.
    identityThe signed-in visitor: a token from your backend, as for askdare('identify'). See below.
    greeting, startersThis page's greeting and up to 4 suggested questions, instead of the bot's.
    contextA short description of the page for the assistant, up to 1,000 characters. Only for a bot with pageContext: true.
    onEventCalled 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.
    toolRenderersYour 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 passing undefined, keeps whoever is signed in. In a single-page app, a Root that stays mounted across a sign-out must get null.
    • 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.

    PropDefaultMeaning
    classNameOn the element that holds the chat. Give it a height.
    headingLevel2The level of the chat's title; the welcome heading is one below. Pick what fits your page's outline.
    colorSchemethe bot's'light', 'dark' or 'auto', for example to follow your site's dark mode switch.
    onCloseShows a close button. Escape, pressed in the chat, calls it too.
    componentsReplaces 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.

    PrimitiveElementWhat it does
    ThemedivSets the bot's tokens (--ask-*) and theme variants for everything inside, and loads the theme and its fonts. Takes colorScheme.
    PanelsectionThe chat's frame, a region named after the bot. Files dropped on it are attached.
    MessagesdivThe 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.
    LoadEarlierbuttonLoads 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.
    MessageListnoneRenders its children once per message.
    MessagedivOne message, with data-role and data-status.
    MessageTextdivThe text: the visitor's as typed, an answer as Markdown, typing dots before the first word.
    MarkdownnoneRenders a text as the chat renders answers.
    CitationsolThe answer's sources.
    ToolApprovaldivA 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.
    ToolResultsdivThe 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.
    Linka or spanA 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.
    MessageFilesul or pThe files sent with a message.
    HandoffButtonbutton"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.
    HandoffStatuspWhere 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.
    FormformOne of the answer's forms (useMessage().forms), drawn from its description in the bot's configuration. See Handoff and forms.
    FeedbackButtonbuttonRates the answer; takes rating="up" or "down". See Answer ratings.
    QuickRepliesdivThe 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.
    ComposerformSubmitting it sends the draft, Enter in the Input included. An onSubmit of yours that calls event.preventDefault() takes the message over.
    InputtextareaThe message field: Enter sends, Shift+Enter starts a new line, pasted files are attached. Your onKeyDown or onPaste can prevent either.
    SendbuttonSends; disabled until there is something to send.
    AttachButtonbuttonOpens the file picker. Renders nothing when the bot takes no attachments.
    FilesulThe files picked for the next message.
    DictateButtonbuttonStarts a dictation. Renders nothing without voice input.
    RecorderdivThe running dictation, with cancel and done. Renders nothing otherwise.
    StatuspWhat the assistant is doing before it writes, or that a conversation is loading.
    ErrorMessagepThe latest problem, in the visitor's language.
    HumanCheckdivThe 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).
    DisclosurepThe 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 }. data is what the tool's ui returned, typed from the tool with ToolRendererProps<typeof tool>. satisfies ToolRenderers<[…]> checks each component against its tool's payload and the tool names; Root also takes a plain map without types. Everything else comes from the hooks.
    • Render data as text. React escapes it. Never pass it to dangerouslySetInnerHTML, and put URLs from it in Chat.Link, which drops javascript: and every other scheme but https, http and mailto. 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. DefaultChat puts the cards under the answer's text. In your own markup, place ToolResults inside MessageList; 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 EmbedRoot from @boldare/askdare/embed and the same toolRenderers. 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.

    • Form renders a form named by its title, then a form-field per field with a visible label. Optional fields say so (form.optional). A select starts with form.choose; a consent field is a checkbox, followed by a link to the bot's privacy policy when widget.disclosure has one. Every text is plain text. Email and phone fields tell the browser what to fill in (autocomplete), and so do fields named name, company and organization.
    • 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-error tied to its field with aria-describedby, the field has aria-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 a form-error with role="alert", and the values stay to try again.
    • Once sent, the form becomes its form-done text, a status: the form's done (or form.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.purpose is lead, handoff (contact details for a person) or message (a message left while nobody is available, titled handoff.unavailableTitle). data-purpose on the form has it, and data-ask-form the form's name.
    • Parts: handoff (the button), handoff-status (with data-state), form, form-title, form-field (with data-type), form-optional, form-error, form-submit (with aria-disabled while it sends) and form-done (with data-state).
    • Your own form. useChat() has everything Form uses: the forms under each message (message.forms: callId, name, purpose, state, handle, and the server's errors by field as text keys), their descriptions in bot.forms, and actions.submitForm(handle, values). Look the error keys up with t; 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.

    • ToolApproval renders a div group (tool-approval, its data-state the card's state) labelled by the summary, which shows as plain text in a p, then the approve and decline buttons (approval.approve, approval.decline). The buttons are disabled while a turn runs and once the card is answered; then a status under the summary says the outcome (approval.approved, approval.declined, approval.expired). Renders nothing on a message without a card.
    • States. message.approval.state is pending until the visitor answers, approved or declined from the moment they do, and expired once 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; a pending one with a fresh handle.
    • Answering starts the bot's next answer, as a message would, without a visitor message of its own.
    • Your own card. useChat() has everything ToolApproval uses: message.approval (callId, name of the tool, summary, state, handle) and actions.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, inside MessageList.
    • useFrame() returns { close } inside EmbedRoot, on your own page in the widget's iframe, and null everywhere else. close asks 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.
    stateMeaning
    phase'starting' on the server and until the chat knows the visitor, 'loading' while a stored conversation loads, then 'ready'.
    busyA turn is under way.
    messagesEach 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).
    earlierOlder messages of a stored conversation: 'more' (load them with loadEarlier()), 'loading', or 'none' once the start shows, or without a stored conversation.
    draft, filesThe message field's text and the files picked for the next message.
    error, activityThe latest problem, and what the assistant is doing before it writes, or "Reconnecting…" (status.reconnecting) while an answer whose connection dropped resumes.
    dictation, elapsed, canDictateThe dictation: 'idle', 'recording' or 'transcribing', its seconds, and whether this browser can record.
    ratings, commentingThe visitor's ratings by message.feedback.key, and the answer the chat asks about after a 👎.
    actionsMeaning
    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 (inside DefaultChat) renders <div data-askdare-root data-ask-bot="support" …> with the variant attributes. Where the widget's docs say :root or <html>, read that element.
    • Your site's CSS reaches the chat. The chat's styles are in @layer askdare and 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 as button { text-transform: uppercase; }, applies to the chat's buttons too.
    • The bot's widget.css still applies, scoped to that bot's chat. :root in 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:

    DirectiveWhy
    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.comThe 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 ui

    It 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 getChatConfig with the new locale and pass the result to Root: 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 or basePath starts another chat. Only a bot with locale: 'auto' switches; see Texts.
    • Sizes (gzipped, in your bundle): about 32 KB for everything, about 10 KB when you use only Root and the hooks. The Markdown renderer is loaded only if you render MessageText or Markdown.