Skip to content

Your backend

Setup 2 of 3

You write the dashboard, the data stays on your server. The components send their queries to one endpoint of your API, which answers with the rights of the signed-in user. No frame, no database in the browser.

Your pageThe tags, written by you
one POST per render: "revenue by country"
Your APIChecks each query, applies the rights of the signed-in user
your SQL
Your dataWarehouse, database, semantic layer

Choose it when you write the dashboards of your product yourself, on data that must not leave your server: too large to download, or not the same for everyone.

Choose another setup when the dashboard is written by a model or by a user: its scripts would run in your page, with your cookies. It goes in the sandbox, which can call the same endpoint. With no server at all, see the static page.

1. The page

Add <source-api> with the address of your endpoint. The components below name measures and dimensions your server knows:

<source-api url="/api/queries"></source-api>

<date-range-filter presets="30d,90d,365d,ytd" default="90d"></date-range-filter>
<ui-filter dimension="channel" type="segmented" label="Channel"></ui-filter>

<score-card measure="revenue"></score-card>
<bar-chart measure="revenue" by="country"></bar-chart>
<line-chart measure="revenue" granularity="month" breakdown-by="channel"></line-chart>
<data-table by="category" measures="revenue, orders" sort-by="revenue"></data-table>

<script src="https://unytics.io/bi-components/dist/bi-components.js" defer></script>

The script is the same file as in a static page. <source-api> is what sends the queries to your server instead of DuckDB-WASM, which is then never downloaded.

A component can also ask with SQL expressions, as in a static page, and a script can ask for a query your server defines:

<!-- SQL expressions -->
<bar-chart table="orders" measure="sum(revenue)" by="country"></bar-chart>

<!-- A named query, for a custom chart -->
<script type="module">
  const { rows } = await window.dashboard.query('category_mix');
</script>

Your endpoint accepts the kinds it wants, and refuses the others: see step 3.

2. The endpoint

The components of a render send their queries together, as one request. Each query has an id; your server gives one answer per id.

POST /api/queries
{
  "queries": {
    "q1": { "mode": "semantic", "metrics": ["revenue"], "dimensions": null, "date_range": ["2026-09-01", "2026-11-29"], "filters": null, ... },
    "q2": { "mode": "semantic", "metrics": ["revenue"], "dimensions": ["country"], ... }
  }
}

200
{
  "answers": {
    "q1": { "rows": [{ "revenue": 592881.64 }], "meta": { "formats": { "revenue": "eur" }, "labels": { "revenue": "Revenue" } } },
    "q2": { "error": "Unknown names: margin" }
  }
}
  • A query describes a chart: named measures and dimensions, or SQL expressions on a table, with the filters and the period selected in the page. It is never a SQL statement: your server writes it.
  • An answer is { rows, meta }, or { error }. The error text is shown in the component that asked, and nowhere else.
  • A refused request (HTTP 4xx or 5xx) fails every query it held, with the detail or error of its body.

Here is a complete server for named measures, with FastAPI and DuckDB. It knows two measures and three dimensions, applies filters, the period and a time granularity, and restricts every query to the countries its viewer may see:

server.py
import duckdb
from fastapi import FastAPI, Request

MEASURES = {  # name: (SQL, label, format)
    "revenue": ("sum(revenue)", "Revenue", "eur"),
    "orders": ("count(*)", "Orders", "int"),
}
DIMENSIONS = ["country", "channel", "category"]
GRANULARITIES = ["day", "week", "month", "quarter", "year"]

db = duckdb.connect()
db.execute("create table orders as select * from read_csv('orders.csv')")
app = FastAPI()


def answer(spec: dict, countries: list[str]) -> dict:
    metrics, dimensions = spec.get("metrics") or [], spec.get("dimensions") or []
    filters, granularity = spec.get("filters") or {}, spec.get("date_granularity")
    unknown = [m for m in metrics if m not in MEASURES] + [d for d in [*dimensions, *filters] if d not in DIMENSIONS]
    if spec.get("mode") != "semantic" or unknown or granularity not in [None, *GRANULARITIES]:
        raise ValueError(f"Unknown names: {', '.join(unknown)}" if unknown else "Unsupported query")

    columns = [*(["date"] if granularity else []), *dimensions]
    select = [f"strftime(date_trunc('{granularity}', date), '%Y-%m-%d') as date"] if granularity else []
    select += dimensions + [f"{MEASURES[m][0]} as {m}" for m in metrics]
    where, values = ["country in (select unnest(?))"], [countries]  # the viewer's rights, on every query
    for dimension, value in filters.items():
        where.append(f"{dimension} in (select unnest(?))")
        values.append(value if isinstance(value, list) else [value])
    if spec.get("date_range"):
        where.append("date between ? and ?")
        values += spec["date_range"]

    sql = f"select {', '.join(select)} from orders where {' and '.join(where)}"
    if columns:
        sort_by = spec.get("sort_by") if spec.get("sort_by") in [*columns, *metrics] else columns[0]
        sql += f" group by all order by {sort_by} {'desc' if spec.get('sort_ascending') is False else 'asc'}"
    if isinstance(spec.get("limit"), int):
        sql += f" limit {min(spec['limit'], 1000)}"
    cursor = db.cursor().execute(sql, values)
    names = [column[0] for column in cursor.description]
    return {
        "rows": [dict(zip(names, row)) for row in cursor.fetchall()],
        "meta": {"formats": {m: MEASURES[m][2] for m in metrics}, "labels": {m: MEASURES[m][1] for m in metrics}, "time_col": "date"},
    }


@app.post("/api/queries")
async def queries(request: Request) -> dict:
    countries = ["France", "Spain"]  # in your application: what the signed-in user may see
    answers = {}
    for id, spec in (await request.json())["queries"].items():
        try:
            answers[id] = answer(spec, countries)
        except ValueError as error:
            answers[id] = {"error": str(error)}  # shown in the component that asked
    return {"answers": answers}

It runs on the orders.csv of the examples, with pip install fastapi uvicorn duckdb then uvicorn server:app, and answers the page of step 1. What matters in it:

  • Names come from lists the server owns. Nothing a query contains is written into the SQL text: names are looked up, values are query parameters.
  • The viewer's rights are added to every query, whatever it asked.
  • meta saves attributes in the page: the format and the label of each measure, and the name of the time column of a time series.

It leaves out comparisons with a previous period (compare="yoy"), stricter checks of what it receives, and the two other kinds of queries, which step 3 adds. Answer the queries describes every field of a query and of an answer, in any language; the server of the playground is a complete version of the one above.

3. SQL expressions and named queries

mode says which kind of query arrives. One endpoint can take all three: rename answer of step 2 to measures, and dispatch.

def answer(spec: dict, countries: list[str]) -> dict:
    match spec.get("mode"):
        case "semantic": return measures(spec, countries)      # step 2
        case "table": return expressions(spec, countries)      # SQL expressions
        case "named": return named(spec, countries)            # a query your server holds
    raise ValueError("Unsupported query")

A named query is the simplest: the page sends a name, with the filters and the period it selected (spec["filters"], spec["date_range"]), and your server holds the SQL. Use the selection or not; answer rows of any shape; refuse a name you do not know.

NAMED = {
    "category_mix": "select category, channel, sum(revenue) as revenue from orders where country in (select unnest(?)) group by all",
}

def named(spec: dict, countries: list[str]) -> dict:
    if spec.get("name") not in NAMED:
        raise ValueError(f"Unknown query: {spec.get('name')}")
    cursor = db.cursor().execute(NAMED[spec["name"]], [countries])
    names = [column[0] for column in cursor.description]
    return {"rows": [dict(zip(names, row)) for row in cursor.fetchall()], "meta": {}}

SQL expressions let the page explore a table freely: sum(revenue), date_trunc('month', date). They are written in the page, so anyone can send any text: your server is the only check. Before any SQL is built, it makes sure that:

  • the table is one you expose, and every word of every expression is one of its columns or a safe function;
  • each expression is one expression: no statement, sub-query, comment or ;;
  • the viewer's rights are added as filters, which apply to every row before any expression is computed.

The library does exactly this, and builds the SQL (DuckDB dialect) from the query. Its functions are plain JavaScript, with no browser needed. In a Node server:

import { compileSQL } from 'bi-components/src/connectors/sql_compiler.js';
import { restrictFilters } from 'bi-components/src/connectors/host-bridge.js';

const TABLES = { orders: ['date', 'country', 'channel', 'category', 'quantity', 'revenue'] };

function expressions(spec, countries) {
  const sql = compileSQL(
    { ...spec, filters: restrictFilters(spec.filters, { country: countries }) },  // the viewer's rights
    { tables: TABLES, dateColumns: { orders: 'date' } },                         // throws for anything else
  );
  return { rows: runOnYourDatabase(sql), meta: {} };   // keyed by the expressions: row['sum(revenue)']
}

It refuses sum(cost) (unknown column), (select 1), read_csv('...'), another table, and the where attribute (a free condition): the page filters with <ui-filter> and clicks instead. restrictFilters keeps a click on an allowed country and refuses one outside the viewer's scope. In another language, apply the same rules with a SQL parser before writing the query, or let a small Node service answer this mode.

Refuse what you do not want. A server with no dictionary of measures refuses semantic; one that exposes no table refuses table. The error text is shown in the component that asked.

Who is looking

Your server decides what each person may see. How it knows who is asking is up to you:

A session cookie Nothing to do: a request to the same site carries its cookies.
A token headers, a property of the element: api.headers = () => ({ authorization: `Bearer ${getToken()}` }). The function is called for each request.
Something the page knows body, a JSON object added to every request: <source-api url="/api/queries" body='{"workspace": "emea"}'>, or the body property (an object or a function).
An API on another site credentials="include", and CORS on that server.

Changing an attribute or a property makes every component ask again:

document.querySelector('source-api').body = { workspace: 'apac' };

Never trust what the page sends to say what its user may see: the page runs in their browser and anyone can call your API with any query. A body selects among things the signed-in user is allowed; the session or the token says who they are.

How queries travel

  • One request per render. The queries asked within 10 ms leave together: the score cards and the charts of a page are one POST, and so is what a click on a filter refreshes. A batch of more than 100 queries is split.
  • The latest query of a component wins. A new query replaces the previous one, whose answer is ignored.
  • A query times out after 30 seconds, with an error in its component.

In a single-page application or a Markdown site

Each <source-api> added to a page installs a new dashboard, with an empty selection, and the components follow it. A site that replaces its content without reloading (a single-page application, the instant navigation of mkdocs-material) thus starts each page fresh, with nothing to call.

Give filters a value at start with default, so that the first render already asks for the right period:

<date-range-filter presets="30d,90d,365d" default="90d"></date-range-filter>
<ui-filter option="period_comparison_method" type="segmented" options="prev_period:vs previous period, yoy:vs last year" default="yoy"></ui-filter>

A page has either a <source-api> or <source-table> elements, not both.

Go further

Example of this setup: a dashboard on a FastAPI backend, a Markdown page of this site, with three viewer profiles whose rights are applied by the server.