Skip to content

Sandbox

Setup 3 of 3

Someone else writes the dashboard: a language model, or one of your users. Its HTML and JavaScript are untrusted code, so they run in an isolated frame that can reach neither your page nor the network. The frame can only ask your page for data, and your application answers with the rights of the person looking at it.

Sandboxed frameThe dashboard, written by a model or a user. No network, no access to your page
asks: "revenue by country"
Your page (the Host)embedDashboard validates each query, then calls your resolveQuery
your call
Your APIChecks again, applies the viewer's rights, answers

Choose it when you do not write the dashboard yourself: generative BI, a "chat with your data", dashboards your customers build, save and share.

Choose another setup when you write every dashboard yourself: tags in your own page are simpler, with your backend or a static page.

1. Embed a dashboard

<div id="dashboard" style="height: 600px"></div>

<script type="module">
  import { embedDashboard } from 'https://unytics.io/bi-components/dist/bi-components-host.js';

  const dashboard = embedDashboard(document.getElementById('dashboard'), {
    html: dashboardHtml,                           // the untrusted part: a string
    resolveQuery: (query) => fetch('/api/query', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify(query),
    }).then((response) => response.json()),        // { rows, meta }
  });
</script>

dashboardHtml is a fragment of HTML made of the same tags as in the other setups, for instance what a model answered:

<h1>Sales overview</h1>
<date-range-filter presets="30d,90d,365d,ytd"></date-range-filter>
<score-card measure="revenue" compare="yoy"></score-card>
<bar-chart measure="revenue" by="country"></bar-chart>

embedDashboard creates an <iframe sandbox="allow-scripts"> in the element you give, which sets its size, writes the dashboard in it, and answers its queries. Your page is called the Host.

What you never do: insert that HTML in your own page. It only ever lives in the frame.

2. Answer the queries

Every query of the dashboard reaches resolveQuery, once validated. It is a description of a chart, never a SQL statement:

{
  "mode": "semantic",
  "metrics": ["revenue"],
  "dimensions": ["country"],
  "filters": { "channel": "Web" },
  "date_range": ["2026-09-01", "2026-11-29"]
}

Return { rows, meta }, or a promise of it. Throw an Error for what you refuse: its message is shown in the component that asked, which is also the text to give back to a model.

resolveQuery: async (query) => {
  const response = await fetch('/api/query', { method: 'POST', body: JSON.stringify(query) });
  if (!response.ok) {
    throw new Error((await response.json()).detail);   // "Unknown metrics: profit_margin"
  }
  return response.json();
},

resolveQuery usually forwards the query to your server. It can also call a semantic layer, or a database running in your page as in the direct queries example. The fields of a query and of an answer are the same as in setup 2: see Answer the queries.

Before your function is called, embedDashboard has already checked the query: a message from its own frame only, lists of plain names, plain values in filters, a bounded limit, unknown fields dropped. What it cannot know is which names exist and who may read them: that is for your server to say.

3. Apply the viewer's rights

A dashboard runs with the rights of the person looking at it, not of its author. Apply them to every query.

In resolveQuery, restrictFilters narrows what was asked to what the viewer is allowed:

import { embedDashboard, restrictFilters } from 'https://unytics.io/bi-components/dist/bi-components-host.js';

resolveQuery: (query) => callYourEngine({
  ...query,
  filters: restrictFilters(query.filters, { country: user.countries }),   // ['France', 'Spain']
}),
  • No filter asked on country: the viewer's countries.
  • A click on France: France only, so cross-filtering still works on a restricted dimension.
  • Only countries outside the viewer's scope: the query is refused.
  • A viewer allowed nothing (an empty list): refused as well. An empty list never means "no restriction".

Then check again on your server. The Host runs in the viewer's browser: these rules stop a dashboard, not a viewer who opens the developer tools. Your endpoint applies the rights of the session to what it receives, as any API does.

4. Named measures, or SQL expressions

A dashboard names data in one of two ways, and query.mode tells you which:

query.mode The dashboard wrote Your part
'semantic' measure="revenue" by="country": names of your dictionary Refuse the names you do not know; compute each measure your way
'table' table="orders" measure="sum(revenue)": SQL expressions on a table Say which tables and columns exist, or refuse the mode
'named' dashboard.query('region_profile') in a script: a query by its name Hold its definition; refuse unknown names

Named measures are the usual choice: one definition of each figure, and nothing but names crosses the frame.

SQL expressions let a dashboard explore a table freely. The Host checks each expression before resolveQuery: one expression, no statement or sub-query, no comment, no function outside a list of safe ones. validateTableSpec adds which tables and columns exist:

import { embedDashboard, validateTableSpec } from 'https://unytics.io/bi-components/dist/bi-components-host.js';

resolveQuery: (query) => {
  if (query.mode !== 'table') {
    throw new Error('This application takes SQL expressions only');
  }
  validateTableSpec(query, { orders: ['date', 'country', 'channel', 'revenue'] });   // throws for anything else
  return runOnYourEngine(query);
},

If your engine does not take them, refuse query.mode === 'table'.

5. Drive the dashboard

embedDashboard returns a handle. Nothing here reloads the frame, except load.

dashboard.setState({ theme: { mode: 'dark' } });                 // theme, filters, period, variables
dashboard.setState({ dateRange: ['2026-01-01', '2026-06-30'] });
dashboard.load(anotherHtml);                                     // another dashboard in the same place
dashboard.state;                                                 // what the viewer selected
dashboard.destroy();                                             // removes the frame

And it tells you what happens in the frame:

embedDashboard(element, {
  html, resolveQuery,
  onReady: () => hideSpinner(),                       // the first render is done
  onStateChange: (state) => rememberForThisViewer(state),
  onRuntimeError: (error) => console.warn(error),     // a script of the dashboard failed
});

Keep what comes from a dashboard private to its viewer: its state and its errors are text chosen by its author. See the security model.

6. Give dashboards a look

A frame starts empty: it gets the components, and what you add for every dashboard.

embedDashboard(element, {
  html, resolveQuery,
  resources: [                                   // stylesheets and scripts every dashboard gets
    'https://cdn.jsdelivr.net/npm/daisyui@5.8.3/daisyui.css',
    'https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4.3.5/dist/index.global.js',
  ],
  css: ':root { --color-primary: #4f46e5; }',    // your own rules, after the stylesheets
  theme: 'dark',
  lang: 'en',
});
Option
resources A list of addresses: stylesheets (.css) and classic scripts (.js). The frame may download these files and no other. They must be served with Access-Control-Allow-Origin, as jsDelivr and GitHub Pages do.
css Rules written in each frame, with no request: your colors, the spacing of the page.
theme 'light' or 'dark' at start. Later: dashboard.setState({ theme: { mode } }).
lang The language of the frame, used for labels, numbers and dates.
title The title of the iframe, read by screen readers.

The rule behind every option: the Host decides, the dashboard never does. The list of files is in your code, and the policy of the frame is fixed before the first line of the dashboard is read. A dashboard cannot import a library by its address: one you want every dashboard to have goes in resources.

A CSS framework for generated dashboards

Without a stylesheet, a model has to write CSS, or you have to describe your own classes in the prompt. A framework the model already knows removes both: it writes class names only.

The playground gives its frames daisyUI (cards, tabs, badges) and the Tailwind browser runtime (layout classes), as in the code above.

  • Both are a single file with no dependency, and work in the sandbox as they are.
  • The components read the daisyUI colors (--color-base-100, --color-primary...), so charts follow the theme. Set your own colors on :root in css.
  • The frame switches theme with data-theme, which is also how daisyUI does it.
  • Tell the model which framework it has, and to never write CSS: see the system prompt.

To make generated dashboards look like your product instead, give the frame your own stylesheet and describe its classes in the prompt.

What a dashboard can and cannot do

It can It cannot
Ask for what your engine allows, within the viewer's rights Send a SQL statement, or get a measure, table or column your engine refuses
Display anything inside its frame, including custom charts Read your page, its cookies, storage or tokens
Set filters and options See more rows than its viewer is allowed to
Run scripts with ECharts and the same data access as the components Send data to another server

What the sandbox guarantees, the attacks it was tested against, and what remains your application's job: Security model.

The files

A Host uses two files, and loads only the first itself:

File Runs Size
bi-components-host.js In your page: embedDashboard, restrictFilters, validateTableSpec 15 KB
bi-components.js In each frame: the components and ECharts About 330 KB compressed, downloaded once for every frame

Each frame loads the bi-components.js found next to bi-components-host.js. When your application serves it elsewhere, for instance with npm and a bundler, give its address with the components option: see Install and versions.

Go further

Examples of this setup: