Skip to content
askdareDocumentation

    Chat events in your analytics

    Marketing wants to know whether visitors use the chat, whether it helps, and whether chatting visitors convert. The chat reports what happens in it to your page as events, which this recipe sends to Google Analytics 4 or Plausible: chats opened, messages sent (typed, a suggested question or a reply option), answers and how long they took, ratings and errors.

    FeatureGuide
    Events from the script tag: askdare('on', '*', listener)Chat events
    Events from the chat inside your page: onEvent on RootChat events: in React

    The code is in site/recipes/analytics/.

    What you can send

    Events carry metadata only: counts, durations, outcomes, ratings and the bot's ID. Never what the visitor or the bot wrote, the page context, or anything about who the visitor is (What events never contain). So they are safe to hand to a third-party analytics script: there is nothing to scrub. Keep it that way: don't add the visitor's message or an ID of yours to what you send.

    1. One mapping for both tools

    From mapping.ts. GA4 gets every event, named chat_<type>; Plausible gets a few goals with custom properties:

    export const toGa4 = ({ type, bot, ...fields }: ChatEventLike) => ({
      name: `chat_${type.replaceAll('.', '_')}`,
      params: {
        chat_bot: bot,
        ...Object.fromEntries(Object.entries(fields).map(([key, value]) => [snakeCase(key), value])),
      },
    });
    
    const PLAUSIBLE_GOALS: Record<string, string> = {
      open: 'Chat opened',
      'message.sent': 'Chat message sent',
      'message.received': 'Chat answer',
      feedback: 'Chat answer rated',
      error: 'Chat error',
    };
    
    export const toPlausible = ({ type, bot, ...fields }: ChatEventLike) => {
      const name = PLAUSIBLE_GOALS[type];
      if (!name) return undefined;
      const props: Record<string, string | number | boolean> = { bot };
      for (const [key, value] of Object.entries(fields)) {
        props[key] = value ?? 'none';
      }
      return { name, options: { props, interactive: type === 'open' || type === 'message.sent' } };
    };
    • GA4 names allow letters, digits and underscores, at most 40 characters, hence chat_message_sent rather than message.sent. A message becomes chat_message_sent with chat_bot, length, attachments and source; an answer chat_message_received with outcome, duration_ms and citations. Register the parameters you want in reports (source, outcome, rating) as custom dimensions in GA4's admin.
    • Plausible shows a custom event only once you add a goal of the same name, capitals included, in the site's settings. Custom properties take strings, numbers and booleans, so a rating taken back (null) is sent as none. Events the visitor didn't cause, an answer arriving or an error, are sent with interactive: false, so they don't change the bounce rate.

    send.ts sends an event to whichever of the two the page loaded:

    export const sendChatEvent = (event: ChatEventLike): void => {
      const page = window as Window & AnalyticsPage;
      const ga4 = toGa4(event);
      page.gtag?.('event', ga4.name, ga4.params);
      const plausible = toPlausible(event);
      if (plausible) page.plausible?.(plausible.name, plausible.options);
    };

    2a. With the script tag

    Register the listener on every page with the chat, after your analytics snippet. Through askdare's queue it works before widget.js has loaded, and then hears ready too. From script-tag.ts:

    export const trackChatEvents = (): void => {
      const page = window as Window & { askdare?: Askdare };
      const askdare: Askdare =
        page.askdare ??
        Object.assign((...args: unknown[]) => void askdare.q?.push(args), { q: [] as unknown[][] });
      page.askdare = askdare;
      askdare('on', '*', sendChatEvent);
    };

    On a page without a bundler, the same in a plain script:

    <script>
      window.askdare = window.askdare || function () {
        (window.askdare.q = window.askdare.q || []).push(arguments);
      };
      askdare('on', '*', function (event) {
        const { type, bot, ...params } = event;
        if (window.gtag) gtag('event', 'chat_' + type.replace('.', '_'), { chat_bot: bot, ...params });
      });
    </script>
    <script src="https://app.example.com/api/chat/widget.js?bot=support" async></script>

    2b. In the chat inside your page

    Root takes the same function as onEvent; React's ChatEvent fits it. From analytics-chat.tsx:

    export function AnalyticsChat({ config }: { readonly config: Chat.ChatConfig }): ReactElement {
      return (
        <Chat.Root config={config} onEvent={sendChatEvent}>
          <Chat.DefaultChat className="help-chat" />
        </Chat.Root>
      );
    }

    React has no open or close: the chat is part of your page, so you know when it shows.

    What to look at

    • Do visitors use the chat? chat_open (script tag) and chat_message_sent per visit.
    • Do reply options help? The share of chat_message_sent with source: reply against typed (Reply options: measure clicks).
    • Are answers good and fast? chat_feedback by rating, and duration_ms of chat_message_received. For why an answer was rated down, read the comment in Answer ratings, on your server.
    • Does it convert? Compare conversions of visits with and without chat_message_sent, or count questions before a sign-up (Chat events: examples).

    Make it yours

    ReplaceWithGuide
    GA4 or PlausibleAny tool with a JavaScript call: a GTM dataLayer.push, Matomo's _paq.push, PostHog's captureChat events: GTM
    The goals in PLAUSIBLE_GOALSThe events you report on. Fewer is easier to read
    ConsentRegister the listener only once the visitor accepted analytics, if your consent banner requires it
    Server-side numbersTokens, costs and tool calls per turn come from onUsage on your server, not from the pageObservability