Embedded analytics guide: build vs buy, iframe vs SDK

How to put customer-facing dashboards inside your product without leaking one tenant's data to another or letting one big customer slow everyone down.

Embedded analytics means showing charts and dashboards inside your own product, scoped so each customer sees only their own data, instead of sending them to a separate BI tool. Getting it right comes down to four decisions: whether to build the charting layer or buy it, whether to integrate through an iframe or a JavaScript SDK, how the viewer’s tenant identity reaches the database, and how to stop one heavy customer from slowing down the rest. The first two decide how much engineering time you spend. The last two decide whether you have a security incident or an outage. Each has a well-understood failure mode. A token that carries the wrong tenant leaks data across customers. An iframe that depends on a third-party cookie shows a login screen in Safari. A shared database user with no per-tenant limits lets one customer’s year-long export starve everyone else’s dashboards. This playbook works through each decision, with SQL tested on ClickHouse 26.10.

What is embedded analytics, and how is it different from internal BI?

Internal BI serves your own employees: a few hundred known users, single sign-on, and a data team on hand when a query is slow. Customer-facing analytics serves your customers’ users, and that changes the requirements:

ConcernInternal BIEmbedded, customer-facing analytics
AudienceEmployees, known by nameThousands of external users you never provision by hand
IdentityYour SSOYour product’s login, passed to the analytics layer
Data scopeRole-based, often broadStrictly one tenant per viewer, every query
Failure costAn annoyed colleagueA cross-customer data leak, a contract breach
Load shapeBusiness hours, predictableFollows your product’s traffic, spiky, many tenants at once
Look and feelThe BI tool’s own UIMust look like your product

The rest of this guide assumes the hard case: a multi-tenant SaaS product where many customers share one warehouse and the embedded views are a feature they pay for.

Build vs buy: what are you actually building?

“Build” rarely means writing a charting library. It means assembling a chart library, a query API, an auth layer, caching, and an admin surface for defining what each chart shows. “Buy” means licensing or self-hosting a BI tool that already has an embedding mode and integrating it.

FactorBuildBuy
Time to first dashboardWeeks to monthsDays to weeks
UI controlTotal: every pixel is yoursTheming and layout options the vendor exposes
Who defines chartsEngineers, in codeAnalysts, in the BI tool, without a deploy
Tenant isolationYou design and audit itYou configure the vendor’s mechanism, and still audit it
Ongoing costEngineering time, foreverLicence or hosting, plus integration upkeep
Self-service (filters, drill-down, ad hoc)Expensive to build wellUsually included

A useful rule: build when the analytics are a few fixed charts tightly woven into a workflow, such as a usage meter on a billing page. Buy when customers expect a dashboard area with filters, drill-down, exports, and new charts every quarter, because then the chart backlog belongs to analysts, not your frontend team. Many products do both: hand-built widgets for the core screens and an embedded BI tool for the “Reports” tab.

Whichever you choose, the security model below is your responsibility. A vendor gives you the mechanism; you decide what goes into the token.

Iframe vs SDK: which integration should you use?

There are three common integration shapes, and most embedded BI tools offer at least two of them.

Plain iframe. Your page renders an <iframe> pointing at a URL that contains a signed token. It is the fastest to ship and isolates the embedded app’s JavaScript and CSS from yours. The costs: the iframe has a fixed height unless the embedded page tells the parent its size, theming is limited to what the URL parameters allow, and clicks inside the frame do not reach your app.

Iframe plus a thin JavaScript wrapper. A small script creates the iframe for you and talks to it over postMessage: auto-resize, click events for drill-through into your own pages, theme switching. You keep the isolation of the iframe and get most of the interactivity people associate with an SDK. Pin the expected origin on every postMessage handler, or any page that frames yours can send forged events.

Component SDK. Charts render as React components or web components directly in your page. This gives the most control over layout and styling, and no frame borders to hide. In exchange, the vendor’s code runs in your page with your page’s privileges, adds to your bundle, and its upgrades become your upgrades.

Plain iframeIframe + wrapperComponent SDK
EffortLowestLowMedium
StylingTheme parameters onlyTheme parameters plus eventsFull CSS control
Isolation from your appStrongStrongNone; same page
Resize and click eventsNoYesNative
Upgrade riskLowLowBundle and framework coupling

Two browser details catch teams out with iframes. First, do not authenticate the iframe with its own session cookie. Inside your product the embedded app is a third party, and Safari’s tracking prevention blocks all third-party cookies by default. The iframe either shows a login screen or nothing. Carry auth in a signed token instead, or use the Storage Access API if you must have a cookie. Second, control who may frame the embedded pages with the frame-ancestors CSP directive, served by the embedded app (or a proxy in front of it), for example frame-ancestors https://app.yourproduct.com. Without it, anyone holding a valid embed URL can show your customer’s data on their own site.

How should tenant identity reach the database?

This is the decision that matters most. The pattern that works everywhere:

  1. The viewer logs in to your product. Your backend already knows their tenant.
  2. Your backend mints a short-lived signed embed token (usually a JWT) whose claims name the tenant, the dashboards or charts allowed, and the row filters to apply.
  3. The browser receives only the token, never the signing secret, and passes it to the embedded app.
  4. The embedded app verifies the signature on every request and turns the claims into query predicates.
// Your backend, after your own login check. Node.js with the jsonwebtoken package.
import jwt from "jsonwebtoken";

app.get("/api/analytics-token", requireLogin, (req, res) => {
  const token = jwt.sign(
    {
      sub: `user-${req.user.id}`,
      tenant_id: req.user.tenantId,          // from YOUR session, never from the request
      dashboards: ["customer-overview"],
      row_filters: { orders: `tenant_id = '${req.user.tenantId}'` },
    },
    process.env.EMBED_SIGNING_SECRET,
    { algorithm: "HS256", expiresIn: "15m" }
  );
  res.json({ token });
});

Four rules keep this safe:

  • Derive the tenant from the server session, never from a request parameter. A classic embedded-analytics leak is an endpoint that takes ?tenant= from the browser and signs whatever it is given.
  • Keep TTLs short. Claims are fixed at mint time. If a user is removed from a customer account, a 24-hour token keeps working for up to 24 hours unless you can revoke it. Minutes, refreshed in the background, beats days.
  • Treat the token as a password. A token in a query string lands in proxy access logs, browser history, and Referer headers. Prefer an Authorization header or a URL fragment, and scrub token parameters from your logs.
  • Make “no filter” an explicit decision. A token with an empty row filter is a full read of every tenant. Your minting code should refuse that unless the caller explicitly says so.

Row-level security: enforce the tenant twice

The embedded app’s filter injection is your first lock. The database should be the second, so that a bug in the application layer returns an error instead of another customer’s rows. Our guide to row-level security in ClickHouse for multi-tenant BI compares row policies, per-tenant tables and per-tenant shards in depth. For embedded analytics on a shared table, a row policy keyed to a per-query setting is a compact pattern:

CREATE ROLE embed_viewer;
GRANT SELECT ON app.orders TO embed_viewer;

-- Every query from this role only sees rows for the tenant named in the
-- custom setting SQL_tenant_id (the SQL_ prefix is allowed by default).
CREATE ROW POLICY tenant_scope ON app.orders
    USING tenant_id = getSetting('SQL_tenant_id')
    TO embed_viewer;

CREATE USER embed_svc IDENTIFIED WITH sha256_password BY 'change-me'
    DEFAULT ROLE embed_viewer;
GRANT embed_viewer TO embed_svc;

The analytics backend then sends the tenant with every query:

SELECT tenant_id, count(), sum(amount)
FROM app.orders
GROUP BY tenant_id
SETTINGS SQL_tenant_id = 'acme';

On a 3-million-row test table spread over three tenants, that query returns only acme’s million rows. Adding WHERE 1 = 1 OR tenant_id = 'globex' changes nothing, because the policy predicate is ANDed with the query’s own filter. And it fails closed: a query sent without the setting stops with Unknown setting 'SQL_tenant_id' rather than returning every tenant’s data.

Two caveats. The setting is only as trustworthy as whoever sets it: this pattern assumes end users never send raw SQL or arbitrary settings, and only your backend talks to ClickHouse. If you expose a SQL editor to customers, give each tenant its own database user and bind the tenant in the user’s settings profile instead. Second, put matching policies on every table the role can read, including dimension tables. A policy on the fact table alone does not stop a join or subquery from reading another tenant’s customers.

How do you keep performance and cost under control?

Customer load does not look like internal BI load. A dashboard with 12 tiles opened by 200 users of one customer at 9 a.m. is 2,400 queries in a few minutes, and the customer’s biggest account can scan a hundred times more rows than the median. Four controls handle most of it.

1. Cap every query. Give the embed role a settings profile that bounds runtime and result size. One gotcha we hit while testing: readonly = 1 blocks all setting changes, including the SQL_tenant_id the row policy needs. Use readonly = 2, which still rejects writes and DDL, and lock the limits with CONST so a query cannot raise them:

CREATE SETTINGS PROFILE embed_limits SETTINGS
    readonly = 2,
    max_execution_time = 10 CONST,
    max_result_rows = 100000 CONST,
    max_concurrent_queries_for_user = 20 CONST
TO embed_viewer;

An attempt to send SETTINGS max_execution_time = 1000 then fails with Setting max_execution_time should not be changed.

2. Budget per tenant, not per database user. All embedded traffic usually arrives through one service user, so a per-user limit is a limit on everyone at once. A ClickHouse quota keyed by a client-supplied key gives each tenant its own counter:

CREATE QUOTA embed_quota KEYED BY client_key
    FOR INTERVAL 1 minute MAX queries = 600, read_rows = 2000000000
TO embed_viewer;

The backend passes the tenant id as the quota key (quota_key in the client or HTTP interface), and system.quotas_usage shows consumption per tenant. With KEYED BY client_key, a query that arrives without a key is refused (QUOTA_REQUIRES_CLIENT_KEY), another useful fail-closed property. Apply the same idea at your API layer: rate-limit per viewer or per tenant, not per token audience, or one chatty customer exhausts the shared bucket.

3. Serve dashboards from pre-aggregated tables. Embedded dashboards ask the same few questions with a different tenant filter. Put tenant_id first in the sort key of every table they read, and back the heavy tiles with daily or hourly rollups, so each query reads one tenant’s slice of a small table. A shared metric definition in a semantic layer keeps “revenue” identical on the embedded dashboard, the internal one and the API.

4. Cache by tenant. A cache key must include the tenant and the full filter set; a cache keyed only on the chart id is a cross-tenant leak with extra steps. Even a 60-second TTL absorbs most of a morning spike, because hundreds of users of one tenant open the same dashboard.

Then measure cost per tenant. Sum read_rows and query duration from system.query_log by tenant each month, and compare the result with what each customer pays. That tells you whether embedded analytics should be a paid tier, and when a large account needs its own replica. For capacity planning, our ClickHouse sizing playbook covers node count and memory. Customer-facing concurrency adds to that baseline, so size for peak dashboard opens, not average queries.

A launch checklist for embedded analytics

  • Tenant id comes from your server session; tokens are signed server-side and expire in minutes.
  • Revocation exists and has been tested.
  • Every table the embed role can read has a row policy, and a query without tenant context fails.
  • frame-ancestors restricts which origins may frame the embed; the iframe needs no third-party cookie.
  • Per-query limits are CONST; per-tenant quotas and API rate limits are on.
  • Cache keys include the tenant and filters.
  • An automated test logs in as tenant A and asserts that no row of tenant B ever comes back, on every dashboard.
  • Cost per tenant is reported monthly.

Where Goni fits

If you would rather buy than build, Goni is one option to evaluate. Full disclosure: this is our product. Goni mints signed embed tokens that carry the viewer’s allow-list, row filters and column masks, enforced through the same access-control path as interactive users. It renders charts and dashboards through chromeless iframe routes or a small JavaScript wrapper with auto-resize and click events, and it lets admins revoke a live token and build embeds from a UI. The drawbacks are real: Goni queries only ClickHouse, so it fits only if that is or will be your warehouse. It is not open source. And it allows any origin to frame its embed routes by default, so restricting frame-ancestors to your domains happens at your reverse proxy or CDN. You can test it against your own data with the 14-day free trial.

FAQ

What is embedded analytics?

Embedded analytics is reporting shown inside another application, such as dashboards in a SaaS product’s “Reports” tab, scoped so each customer sees only their own data. Unlike internal BI, the viewers are external users who log in to your product, not to a BI tool. Your app passes their identity and tenant to the analytics layer, usually as a signed token.

Is iframe embedding secure?

An iframe is as secure as the token and the server behind it. Sign tokens server-side with a short expiry, derive the tenant from your own session, and enforce row filters on the server, ideally twice, in the app and in the database. Restrict who may frame the pages with frame-ancestors and keep tokens out of logs.

How do you embed a dashboard in a web app?

Your backend checks the user’s login, mints a signed token naming their tenant and the dashboard, and returns it to the browser. The page then renders an iframe or SDK component with that token. The embedded app verifies the signature on each request and applies the token’s row filters to every query it runs.

How do you do multi-tenant row-level security for embedded analytics?

Enforce the tenant in two layers. The analytics app injects a tenant filter from the signed token into every query, and the warehouse enforces its own rule, such as a ClickHouse row policy, so an application bug returns an error instead of foreign rows. Cover every readable table, including dimensions, and test cross-tenant access automatically.

Should you build or buy embedded analytics?

Build when you need a handful of fixed charts woven into a workflow and want total control of the UI. Buy when customers expect a full dashboard area with filters, drill-down, exports and frequent new charts, because analysts can then ship those without frontend deploys. Either way, the tenant-isolation design remains your responsibility.