Business Intelligence

How to Embed Analytics in a React App (Full Tutorial)

Build customer-facing analytics in React on Querio's Embedded API: an Express route that guards each customer's data, a polling hook, and a themed table and chart.

Javier BonillaCo-founder & CTO

You want customers to ask a question inside your React app and see their own numbers as a table and a chart that look like the rest of your product. Put a small server route between React and Querio's Embedded API. It holds the token, sets the customer from the session on every new question and checks it on every request after that. React then waits for the answer and draws it with your own components.

That route is the part that's easy to get wrong. Your Querio token speaks for your whole workspace, and a request that reads a conversation or fetches its table names only the conversation, not your customer. Your route is the one place that knows who is asking, so it checks every time.

What are you building?

Six short files, all shown in full below:

  • server.js: an Express route that keeps the Querio token on your server and decides which customer every request is for.
  • useConversation.js: a React hook that asks a question, waits for the answer and handles follow-ups.
  • AnswerParts.jsx, QuerioTable.jsx and QuerioChart.jsx: the components that draw an answer's text, table and chart.
  • AskYourData.jsx: the component you put on a page.

Built with React 19.3, vega-embed 7.3 (with Vega 6.4 and Vega-Lite 6.5), Express 5.3 and Node 26, against version 2.1.0 of Querio's Embedded API.

If you haven't set Querio up for embedding yet (connecting the data, writing its context, creating the API token), or you're still deciding between an iframe and an API, start with how to embed dashboards in your SaaS product. An iframe of a shared board is enough when every viewer may see the same numbers. This tutorial is for when each customer sees only their own and can ask the next question.

How should the Express route talk to Querio?

Your React code never calls Querio. It calls your server, and your server calls Querio with the token:

// server.js
// Querio Embedded API v2 (OpenAPI 2.1.0): https://docs.querio.ai/embed/api
import express from "express";

const QUERIO = "https://app.querio.ai";
const SLUG = process.env.QUERIO_CUSTOMER_SLUG; // the slug Querio assigned to your organization
const TOKEN = process.env.QUERIO_API_TOKEN;    // created in Querio under Embedded > API Tokens

const app = express();
app.use(express.json());
// Your own auth middleware goes here. It sets req.user from the session:
// req.user = { id: "u_42", accountId: "acme-corp" }

async function querio(path, init = {}) {
  const res = await fetch(`${QUERIO}${path}`, {
    ...init,
    headers: { Authorization: `Bearer ${TOKEN}`, "Content-Type": "application/json" },
  });
  const body = res.status === 204 ? null : await res.json();
  return { status: res.status, body };
}

const base = `/api/v2/embed/${SLUG}/conversations`;

// Start a conversation. The customer comes from the session, never from the browser.
app.post("/api/analytics/conversations", async (req, res) => {
  const { status, body } = await querio(base, {
    method: "POST",
    body: JSON.stringify({
      prompt: req.body.prompt,
      datasourceSlug: "orders",
      model: "claude-sonnet-5-5",
      scope: { customer_id: req.user.accountId },
      environment: process.env.NODE_ENV === "production" ? "production" : "testing",
      tags: { user_id: req.user.id },
    }),
  });
  res.status(status).json(body);
});

// List this customer's past conversations. The filter always comes from the session.
app.get("/api/analytics/conversations", async (req, res) => {
  const qs = new URLSearchParams({ "scope.customer_id": req.user.accountId, limit: "20" });
  if (req.query.cursor) qs.set("cursor", req.query.cursor);
  const { status, body } = await querio(`${base}?${qs}`);
  res.status(status).json(body);
});

// Read a conversation. Check it belongs to this customer before returning it.
app.get("/api/analytics/conversations/:id", async (req, res) => {
  const { status, body } = await querio(`${base}/${req.params.id}`);
  if (status === 200 && body.scope?.customer_id !== req.user.accountId) return res.sendStatus(404);
  res.status(status).json(body);
});

// Ask a follow-up in the same conversation, after the same check.
app.post("/api/analytics/conversations/:id/turns", async (req, res) => {
  const convo = await querio(`${base}/${req.params.id}`);
  if (convo.status !== 200 || convo.body.scope?.customer_id !== req.user.accountId) return res.sendStatus(404);
  const { status, body } = await querio(`${base}/${req.params.id}/turns`, {
    method: "POST",
    body: JSON.stringify({ prompt: req.body.prompt }),
  });
  status === 204 ? res.sendStatus(204) : res.status(status).json(body);
});

// Fetch a table page or a chart spec, after the same check.
app.get("/api/analytics/conversations/:id/assets/:cellId", async (req, res) => {
  const convo = await querio(`${base}/${req.params.id}`);
  if (convo.status !== 200 || convo.body.scope?.customer_id !== req.user.accountId) return res.sendStatus(404);
  const qs = new URLSearchParams(req.query).toString();
  const { status, body } = await querio(`${base}/${req.params.id}/assets/${req.params.cellId}${qs ? `?${qs}` : ""}`);
  res.status(status).json(body);
});

app.listen(3000);

Three things in this file do the real work.

The customer is set once, from your session. A new conversation carries scope.customer_id, the scope variable Querio uses for row-level security, so every answer in that conversation is built from that customer's rows. The browser only sends the question. If the customer id came from the browser, anyone could change it.

Every request after that checks the customer again. Getting a conversation, posting a follow-up and fetching a table or chart: before passing any of them on, your route compares the conversation's scope.customer_id with the signed-in customer. The follow-up and asset routes each read the conversation first to do it. The list route does the same job by always setting the scope.customer_id filter itself, so a customer can't drop it or swap in someone else's id.

A wrong customer gets 404, not 403. A 403 tells the caller the id exists. A 404 says nothing.

Tags are labels you choose. Here user_id lets you list one user's past questions later. environment lets you filter test conversations apart from production ones.

How does React wait for the answer?

Querio answers in the background. Starting a conversation returns a conversationId right away, with the conversation in PENDING status. It moves to RUNNING while the agent works, and ends COMPLETED or FAILED. You poll until it ends:

// useConversation.js
import { useEffect, useState } from "react";

const API = "/api/analytics/conversations";

export function useConversation() {
  const [id, setId] = useState(null);
  const [convo, setConvo] = useState(null);
  const [polling, setPolling] = useState(false);
  const [error, setError] = useState(null);

  async function ask(prompt) {
    setError(null);
    const res = id
      ? await fetch(`${API}/${id}/turns`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt }) })
      : await fetch(API, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt }) });
    if (res.status === 409) return setError("Still answering the last question.");
    if (!res.ok) return setError("Couldn't send that question.");
    if (!id) setId((await res.json()).conversationId);
    setPolling(true);
  }

  useEffect(() => {
    if (!id || !polling) return;
    let stop = false;
    async function poll() {
      const res = await fetch(`${API}/${id}`);
      if (stop) return;
      if (!res.ok) { setPolling(false); return setError("Couldn't load the answer."); }
      const data = await res.json();
      setConvo(data);
      if (data.status === "COMPLETED" || data.status === "FAILED") return setPolling(false);
      setTimeout(poll, 1500);
    }
    poll();
    return () => { stop = true; };
  }, [id, polling]);

  return { convo, ask, busy: polling, error };
}

The first question starts a conversation. Every later one is a follow-up turn in the same conversation, so "Only October and November" means what the customer meant, and the new answer is added to the same message history. A follow-up sent while the last turn is still running gets a 409 from Querio. The hook shows a short message instead of failing, and the page disables the Ask button while it waits, so it rarely happens.

The stop flag is for the customer who leaves the page mid-answer. The cleanup sets it, so a poll that comes back late doesn't touch the state of a component that's gone, and no new poll is scheduled.

The four states a Querio conversation moves through and what the React page shows in each: PENDING and RUNNING show "Working on it" with the Ask button disabled; COMPLETED shows the answer's text, table and chart; FAILED shows a message asking the customer to rephrase. A follow-up question sends the conversation back to PENDING.

How do you draw the table and the chart?

An answer is a list of parts. A text part is plain text. A data-table part and a data-chart part each carry a title and a URL to fetch the full asset from. That URL is a Querio API path, like /api/v2/embed/{slug}/conversations/{id}/assets/{cellId}, which needs the token. So AnswerParts points it at your own route instead:

// AnswerParts.jsx
import { QuerioChart } from "./QuerioChart.jsx";
import { QuerioTable } from "./QuerioTable.jsx";

// Querio's asset url is "/api/v2/embed/{slug}/conversations/{id}/assets/{cellId}".
// Send the browser to your own route with the same conversation and asset id.
const proxied = (url) => url.replace(/^\/api\/v2\/embed\/[^/]+\/conversations/, "/api/analytics/conversations");

export function AnswerParts({ message }) {
  return message.parts.map((part, i) => {
    if (part.type === "text") return <p key={i}>{part.text}</p>;
    if (part.type === "data-table") return <QuerioTable key={i} url={proxied(part.data.url)} />;
    if (part.type === "data-chart") return <QuerioChart key={i} url={proxied(part.data.url)} />;
    return null;
  });
}

Tables come back a page at a time: 20 rows by default, up to 10,000 per page. Each response has the columns with their types, the rows, and totalRows, which is all a pager needs:

// QuerioTable.jsx
import { useEffect, useState } from "react";

export function QuerioTable({ url, pageSize = 20 }) {
  const [page, setPage] = useState(1);
  const [table, setTable] = useState(null);
  useEffect(() => {
    fetch(`${url}?page=${page}&pageSize=${pageSize}`).then((r) => r.json()).then(setTable);
  }, [url, page, pageSize]);
  if (!table) return null;
  const pages = Math.ceil(table.totalRows / table.pageSize);
  return (
    <div>
      <table>
        <thead><tr>{table.columns.map((c) => <th key={c.name}>{c.name}</th>)}</tr></thead>
        <tbody>
          {table.rows.map((row, i) => (
            <tr key={i}>{table.columns.map((c) => (
              <td key={c.name} className={c.type === "integer" || c.type === "number" ? "num" : ""}>{String(row[c.name] ?? "")}</td>
            ))}</tr>
          ))}
        </tbody>
      </table>
      {pages > 1 && (
        <nav>
          <button disabled={page === 1} onClick={() => setPage(page - 1)}>Previous</button>
          <span>Page {page} of {pages}</span>
          <button disabled={page === pages} onClick={() => setPage(page + 1)}>Next</button>
        </nav>
      )}
    </div>
  );
}

The column type (string, integer, number, boolean, datetime) tells you which cells to right-align. The same asset also takes query, sort and filters parameters if you want search and sorting on the table, and the route above passes them through.

Charts come back as a Vega-Lite spec, an open JSON format for charts. You draw it with vega-embed and hand it your own styles as config. No Querio component goes into your bundle.

How do you make the charts follow your design system, in light and dark mode?

Don't hard-code a second copy of your colors for the charts. Read the CSS variables your app already uses, and draw the chart again when the color scheme changes:

// QuerioChart.jsx
import { useEffect, useRef, useState } from "react";
import embed from "vega-embed";

// Build the chart theme from the CSS variables your app already uses.
function themeFromCss() {
  const css = getComputedStyle(document.documentElement);
  const v = (name) => css.getPropertyValue(name).trim();
  return {
    font: v("--font-sans"),
    background: null,
    mark: { color: v("--color-accent") },
    bar: { cornerRadiusTopLeft: 3, cornerRadiusTopRight: 3 },
    axisX: { labelAngle: 0 },
    axis: { labelColor: v("--color-muted"), titleColor: v("--color-muted"), gridColor: v("--color-line"), domain: false, ticks: false },
    title: { anchor: "start", fontSize: 15, fontWeight: 600, color: v("--color-text") },
    view: { stroke: null },
  };
}

function useColorScheme() {
  const query = "(prefers-color-scheme: dark)";
  const [dark, setDark] = useState(() => matchMedia(query).matches);
  useEffect(() => {
    const media = matchMedia(query);
    const onChange = (e) => setDark(e.matches);
    media.addEventListener("change", onChange);
    return () => media.removeEventListener("change", onChange);
  }, []);
  return dark ? "dark" : "light";
}

export function QuerioChart({ url }) {
  const ref = useRef(null);
  const scheme = useColorScheme();
  useEffect(() => {
    let result;
    let cancelled = false;
    fetch(url)
      .then((r) => r.json())
      .then((spec) => (cancelled ? null : embed(ref.current, spec, { config: themeFromCss(), actions: false, renderer: "svg" })))
      .then((r) => { result = r; if (cancelled) r?.finalize(); });
    return () => { cancelled = true; result?.finalize(); };
  }, [url, scheme]);
  return <div ref={ref} style={{ width: "100%" }} />;
}

Change the variable names to yours. If your app switches themes with a class instead of the system setting, pass that theme in as a prop and use it in place of scheme.

A few details in this component save you a debugging session:

  • width: "container" needs a parent with a width. Querio's chart specs ask for the width of their container, so the wrapper div is set to 100%. Inside a flex row, give it a width too.
  • finalize() on cleanup. vega-embed's finalize() frees the chart's view and listeners. Without it, every re-draw leaves the old one behind.
  • actions: false hides vega-embed's export and view-source menu, which your customers don't need.
  • axisX: { labelAngle: 0 } keeps short labels like month names level instead of turned sideways.

The same answer drawn twice by the components in this tutorial: in light mode with blue bars on a pale background, and in dark mode with lighter blue bars on a near-black background. Both show the text "Here are your orders by month for the last six months," a table of orders by month from June to November, and a bar chart of the same numbers.

How do you put it on a page?

The last file ties the others together:

// AskYourData.jsx
import { useState } from "react";
import { useConversation } from "./useConversation.js";
import { AnswerParts } from "./AnswerParts.jsx";

export function AskYourData() {
  const { convo, ask, busy, error } = useConversation();
  const [prompt, setPrompt] = useState("");
  return (
    <section>
      <form onSubmit={(e) => { e.preventDefault(); ask(prompt); setPrompt(""); }}>
        <input value={prompt} onChange={(e) => setPrompt(e.target.value)} placeholder="Ask about your orders" />
        <button disabled={busy || !prompt}>Ask</button>
      </form>
      {busy && <p>Working on it…</p>}
      {error && <p role="alert">{error}</p>}
      {convo?.status === "FAILED" && <p role="alert">That question didn't work. Try asking it another way.</p>}
      {convo?.messages.filter((m) => m.role === "assistant").map((m) => <AnswerParts key={m.id} message={m} />)}
    </section>
  );
}

Drop <AskYourData /> into any page behind your login. Each answer stays on screen, and the next question's answer appears under it.

How do you prove one customer can't read another's answers?

Run three checks before a customer sees this:

  1. Two test customers, two answers. Sign in as two test accounts and ask both the same question. Each should get numbers from its own rows.
  2. Swap the conversation id. Signed in as the second customer, request the first customer's conversation, and one of its assets, through your routes. Both should return 404. Then call the list route with ?scope.customer_id= set to the first customer: you should still see only the second customer's conversations.
  3. Search the build for the token. Build your front end and search the output for the token. Zero matches.

Keep test traffic on environment: "testing". The Control Center shows the requests your app sends and the shape of each response.

Each question uses AI credits, and every conversation reports how many AI generations it used in metadata.aiGenerations. So send a prompt when a customer asks one, never on page load just to draw the same chart. Querio Embedded is an add-on to any plan, from $1,500 a month with 7,500 AI credits a month.

For how tenants stay apart in the data itself, read row-level security for multi-tenant SaaS analytics. If you're comparing embedded analytics platforms for a React app, this is the test that matters: can your server, not the vendor's widget, decide which customer every request is for?

Magic happens when
people and agents work together