Embedding a dashboard in a React app comes down to five moving parts: the data source behind the dashboard, the tenant identifier that scopes it to one customer, an embed URL the browser can load, a container component that renders it, and a server-side token mint step that keeps secrets out of the frontend. Done right, every customer who opens your <Dashboard /> component sees only their own data, under your brand, without ever leaving your app. Done casually, you get a demo that works in development and a tenant-isolation bug waiting to ship.

Most teams underestimate the gap between those two outcomes. The iframe tag itself takes ninety seconds. Everything around it, passing the right customer identity, keeping secrets server-side, handling re-renders, SSR, and responsive sizing, is where the actual work lives. This walkthrough covers all of it in React, with notes on the Next.js specifics that bite people (App Router, SSR, route handlers for token minting).


React code example showing a component that embeds a customer dashboard iframe
Photo: Ferenc Almasi / Unsplash

What you are actually embedding

An embedded dashboard is a live analytics view rendered inside your application, not a screenshot and not a separate BI tab. In a React app it almost always arrives as one of three things:

  • An iframe pointing at a hosted dashboard URL. The simplest and most common pattern. Your app supplies the URL (plus a token), the browser renders the vendor’s page inside your layout.
  • A JavaScript SDK component. Some analytics vendors ship a React-friendly embedder that gives you more control over initialization, resizing, and events.
  • Native components your team builds. Full control, full ownership: your charting library, your query layer, your tenant filtering, your maintenance bill forever.

This guide uses the iframe pattern with a hosted dashboard, because it is what embedded analytics platforms like embedding a dashboard in a SaaS application generally look like in production, and it keeps your frontend free of secrets. The React-specific mechanics apply to the SDK pattern too.

The five parts of a React dashboard embed

PartLives inJob
Data sourceYour database / APIPowers the dashboard: PostgreSQL, MySQL, Firebase, REST APIs, CSV, Sheets
Tenant identifierYour session / auth layerTells the dashboard which customer’s data to show (e.g. org_id=1234)
Embed URL + tokenYour serverA scoped, signed URL the browser can load without seeing your API secret
Container componentYour React appRenders the iframe, sizes it, handles loading states and token refresh
Styling / white-labelDashboard configLogo, colors, dark mode so the dashboard reads as part of your product

The rule that makes this secure: the tenant identifier and the signing secret must be combined in a trusted place (your server), never in the browser. If the frontend can pick which org_id to request, you have built a dashboard-shaped IDOR bug. The JWT authentication guide covers that threat model in depth; here we wire it into React.

Step 1: Build the dashboard and its tenant parameter

Create the dashboard once, as a template, and give it a customer filter. One reusable dashboard serving every tenant beats one dashboard per customer on every axis that matters: maintenance, upgrades, bug fixes, consistency.

Concretely, your dashboard query should consume a tenant parameter supplied at view time:

-- Dashboard template query (PostgreSQL source)
SELECT day, events_count
FROM daily_usage
WHERE organization_id = {{tenant_id}}
ORDER BY day DESC
LIMIT 90;

The {{tenant_id}} placeholder is filled in when a specific customer opens the embed, not baked into the dashboard. If your data lives in Postgres, MySQL, Firebase, a REST API, CSV, or Google Sheets, most embedded analytics tools (Embedful included) treat them as first-class sources, so this step happens in the dashboard builder rather than in React code.

Step 2: Mint the embed token on your server

The browser must never know your analytics API key. The pattern is a small backend endpoint that takes the logged-in user’s session, derives their organization, and returns a short-lived signed embed URL or token:

// Express route (same shape as a Next.js route handler)
app.get("/api/embed-url", requireAuth, async (req, res) => {
  const orgId = req.user.orgId;              // from verified session, not the client
  const token = signEmbedToken({
    tenant: orgId,
    exp: Math.floor(Date.now() / 1000) + 300, // 5-minute expiry
  }, process.env.EMBEDFUL_SECRET);            // server-side secret
  res.json({ url: `${DASHBOARD_URL}?token=${token}` });
});

Three properties make this the right shape: the tenant comes from your session (the client cannot claim to be someone else’s org), the token expires quickly, and the signing secret never ships in a JS bundle. In Next.js App Router, the same logic goes in a route handler at app/api/embed-url/route.ts, which runs on the server and can read environment variables safely.

Step 3: Render the iframe in a React component

The container component fetches the embed URL, keeps it in state, and re-fetches when the token expires. A production-ready version with loading state and refresh:

function DashboardEmbed({ orgId }) {
  const [url, setUrl] = useState(null);

  useEffect(() => {
    let cancelled = false;
    const load = async () => {
      const res = await fetch("/api/embed-url", { credentials: "include" });
      const data = await res.json();
      if (!cancelled) setUrl(data.url);
    };
    load();
    const id = setInterval(load, 4 * 60 * 1000); // refresh before 5-min expiry
    return () => { cancelled = true; clearInterval(id); };
  }, [orgId]);

  if (!url) return <Skeleton height={640} />;
  return (
    <iframe
      key={url}                 // remount on token rotation
      src={url}
      title="Your account dashboard"
      style={{ width: "100%", height: 640, border: 0 }}
      loading="lazy"
    />
  );
}

Two details in that snippet do real work. The key={url} forces a clean remount when the token rotates, which avoids half-initialized iframe states. The cleanup function cancels the in-flight refresh on unmount, which is the React idiom for “do not setState on a dead component” and prevents stale-token races when users switch tenants fast.

Step 4: Pass the tenant identity from your session

The orgId prop above should come from your authenticated app state, never from a URL query parameter that anyone can type. The trust chain looks like this:

User logs in
  -> Your server knows their organization (session/JWT claim)
  -> React reads orgId from the session API, not from location.search
  -> /api/embed-url signs a token for that org only
  -> Dashboard filters every query by the verified tenant

If you need to pass more than a tenant ID into the dashboard (plan tier, feature flags, user role), pass them as claims in the signed token, not as plain URL parameters. Plain parameters are suggestions; signed claims are facts the dashboard can trust. This is exactly what row-level security on the data layer enforces underneath: the tenant filter belongs to the data-access layer, and the token is how the browser proves which tenant it is.

Step 5: Next.js specifics: SSR, route handlers, hydration

Next.js App Router changes three things about the pattern above:

  • The iframe component must be client-side. Mark it "use client"; useEffect, useState and interval refreshes do not run during server rendering. The SSR pass renders your skeleton, the browser fetches the real embed URL on hydration, so first paint stays fast and no token ever appears in server HTML.
  • Token minting belongs in a route handler. app/api/embed-url/route.ts executes on the server with full env access. Never call your analytics API from a Server Component that returns the URL as a prop into serialized RSC payloads; that puts embed tokens in HTML and caches.
  • Dynamic pages, not static. A page rendering per-tenant dashboards must be dynamic (dynamic = "force-dynamic" or session-based cookies() reads). Static generation bakes one tenant’s context into a shared artifact, which is the SSR flavor of the same isolation bug.

Pages Router users get the same shape with getServerSideProps for session data and an API route for token minting. The rule in every router version: identity and secrets resolve server-side, the iframe consumes only a short-lived signed URL.

Responsive sizing: the part everyone skips

A fixed 640px iframe looks fine on your dev laptop and broken on a customer’s tablet. Two practical patterns:

  • Fixed height, fluid width (the snippet above). Simple, predictable, works when the dashboard has a known layout height. Set width: 100%, pick a height that fits your widget grid, add a mobile breakpoint via CSS.
  • postMessage auto-resize. The embedded page posts its content height to the parent; your component listens and sets iframe height dynamically. More moving parts, best when dashboard heights vary per tenant.

Test on real devices before shipping. Customers open dashboards on phones more than teams expect, and a chart clipped by a 320px iframe is a support ticket with a screenshot attached.

Common React embed mistakes

  • Tenant ID from the URL. If ?org= is in the query string, someone will change it. Derive tenant from session only.
  • API key in frontend env. Anything prefixed for the browser ships to the browser. Next.js NEXT_PUBLIC_* variables are public by design; keep analytics secrets unprefixed and server-side.
  • Long-lived embed tokens in localStorage. Cache-busting becomes a security incident. Mint short-lived tokens per view, refresh on interval.
  • Re-rendering the iframe on every parent state change. Memoize the URL; use key intentionally, not accidentally. An iframe that reloads on each keystroke makes dashboards feel broken.
  • No loading or error state. Token endpoint hiccups show customers a blank box. Skeleton plus retry is cheap insurance.

Where Embedful fits

If you do not want to own the query layer, tenant filtering, and iframe hosting yourself, the platform path is: connect a data source (PostgreSQL, MySQL, Firebase, API, CSV/Excel, Sheets, GA4), build one template dashboard with a customer parameter, then generate signed embed URLs from your server. Embedful’s customer-facing features (customer dashboards, unlimited viewers, white-label branding, password protection, automatic refresh) sit on the Pro plan at $71 per month and Agency at $159 per month, verified against the live pricing page; Starter covers internal reporting only. The React integration is exactly the pattern above: server mints a scoped URL, your component renders it, white-label settings make it look native.

Building natively in React still makes sense when analytics is your core product surface and you have the engineering capacity to own isolation code, caching, and chart maintenance for years. For most SaaS teams shipping a customer dashboard this quarter, build vs buy lands on buy.

FAQ: embedding dashboards in React

Can I embed a dashboard in React without an iframe?

Yes, via a vendor JavaScript SDK (more control over events and sizing) or fully native components (maximum control, maximum maintenance). The iframe pattern is the default because it isolates the analytics runtime from your app’s CSS and JS, and every modern platform supports it.

How do I keep customer data isolated inside the embedded dashboard?

Enforce the tenant filter in the data-access layer, and pass tenant identity only through server-signed tokens derived from the logged-in session. Frontend filtering is presentation, not isolation. The multi-tenant analytics guide walks the full architecture.

Does this work with Next.js App Router?

Yes. Keep the iframe component client-rendered, mint tokens in a route handler (app/api/embed-url/route.ts), and keep tenant pages dynamic so no customer’s context is ever statically generated.

How often should the embedded dashboard refresh?

Match the data to the use case: operational dashboards want minutes, billing and usage summaries are fine hourly or daily. Check what refresh cadence your plan supports before promising customers live numbers; Embedful Pro includes automatic scheduled refresh.

What is the fastest way to prototype this?

Spin up one template dashboard on a free analytics account, wire a dev token endpoint that signs for a test org, and render the iframe in a sandbox route. You can validate the full flow (data, tenant scoping, embed, styling) in an afternoon before committing to any plan.


Related Articles

Ready to wire one in? Start free with Embedful and render your first tenant-scoped dashboard inside React today.

Sources