Embedding a dashboard in a Next.js app is an iframe, a server-side token mint, and about 30 lines of glue code. The iframe renders the dashboard inside your product, a route handler on your Next.js server signs a short-lived token that identifies the tenant, and a client component passes that URL into the frame. Done right, every customer sees only their own data, the dashboard stays under your brand, and no analytics infrastructure gets built.

Most teams get the iframe working in an afternoon, then spend weeks on the parts that actually matter: hydration errors, token minting leaking into client bundles, tenant parameters anyone can edit, and dashboards that resize badly inside App Router layouts. This guide walks through the whole path end to end with Next.js App Router specifics: where each piece of code runs, how to pass the signed URL without breaking SSR, and a decision table for plain React versus Next.js-specific patterns.

By the end you will have a working /dashboard route that renders a tenant-scoped dashboard inside your app, with the token minted server-side and nothing secret in the browser bundle.


Next.js dashboard embed: code editor showing React source with a client analytics dashboard on screen
Photo: Juanjo Jaramillo / Unsplash

What embedding a dashboard in Next.js really involves

An embedded dashboard is a hosted view of your data, framed inside your app. In Next.js App Router terms, the pieces split across the server/client boundary like this:

PieceWhere it runsWhat it does
Dashboard definitionAnalytics platform (server-side)Queries your database or API and renders charts
Tenant token mintNext.js route handler (server)Signs a short-lived JWT binding the session user to their tenant ID
Iframe componentClient componentRenders the frame, handles resize and loading states
Session lookupServer component / route handlerMaps the logged-in user to their tenant ID from your database
URL assemblyServer (recommended)Combines dashboard URL + token so secrets never ship to the browser

The security-critical rule sits in row two: the signing key belongs on the server. A route handler at app/api/embed-token/route.ts is the canonical place, per the Next.js route conventions. If your signing secret ends up in a client component, it is public within minutes; anyone can read a shipped JS bundle.

If you are new to embedding generally, the React embed guide covers the same architecture for plain React apps. This post goes deeper on App Router: server components, route handlers, hydration, and metadata.

Plain React vs Next.js: what actually changes

The iframe is identical in both stacks. What changes is where the token gets minted and how the URL reaches the component:

ConcernPlain React (CRA/Vite)Next.js App Router
Token mintingSeparate API server you run yourselfRoute handler in the same app (app/api/.../route.ts)
Passing the URL to the iframeFetch in a useEffectServer component fetch, pass as prop; no client fetch needed
Secrets exposure riskYou must keep keys off the frontend by disciplineEnforced: server components and route handlers never ship code to the browser
SSR/hydration pitfallsNone (CSR only)Client-only APIs (window, resize observers) need "use client" boundaries
Page metadata, SEO of the shellManualgenerateMetadata on the dashboard route

The App Router model is genuinely safer here: code in a server component (no "use client" directive) is stripped from the client bundle by the compiler, so your signing secret physically cannot leak through it. That is an advantage over a React SPA talking to a separate API, not a style preference.

Step 1: Build the dashboard with a tenant parameter

The dashboard needs one input that says which customer it renders for. In practice that is a URL parameter your analytics platform substitutes into every query, for example ?tenant_id=acme-corp. Two rules make this safe:

  • The parameter must be verified server-side. A token signed by your app proves the tenant ID; a raw query string does not. The JWT guide covers the claim structure: see JWT authentication for embedded dashboards.
  • Every query must enforce it. A dashboard that filters by a user-supplied parameter without enforcement is one tampered request away from cross-tenant leaks. Row-level security in the database is the durable fix, covered in row-level security for SaaS.

The dashboard itself can read from your Postgres database, a REST API, Firebase, or a spreadsheet. The data source choice is independent of the Next.js embedding mechanics; each has its own guide on this blog (REST API, Firebase, Google Sheets).

Step 2: Mint the embed token in a route handler

Create app/api/embed-token/route.ts. It reads your session, resolves the tenant, signs a short-lived JWT, and returns the signed embed URL. The signing key lives in server environment variables only.

// app/api/embed-token/route.ts  (App Router route handler)
import { NextResponse } from "next/server";
import { SignJWT } from "jose"; // works on edge and node runtimes

export async function GET(req: Request) {
  const session = await getSession(req); // your auth layer
  if (!session?.user) return NextResponse.json({ error: "unauthorized" }, { status: 401 });

  // Resolve tenant from YOUR database, never from the request body.
  const tenantId = await lookupTenantForUser(session.user.id);

  const token = await new SignJWT({ tenant_id: tenantId })
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setExpirationTime("10m") // short-lived on purpose
    .sign(new TextEncoder().encode(process.env.EMBED_SECRET));

  const embedUrl =
    `https://app.embedful.io/embed/dashboard/your-dashboard-id` +
    `?tenant_id=${encodeURIComponent(tenantId)}&token=${token}`;

  return NextResponse.json({ url: embedUrl });
}

Three details in that handler carry the security of the whole feature:

  • Tenant comes from your database, keyed by the authenticated session, never from a query parameter the browser controls.
  • The token is short-lived (5-10 minutes). If it leaks through logs or history, its window of usefulness closes on its own.
  • The handler returns a URL, not the secret. The browser receives a signed artifact it cannot forge.

Route handlers run on the Node runtime by default; if you deploy to edge, pick a JWT library that supports Web Crypto (the jose example above does). Full conventions in the official Next.js route handler reference linked at the bottom.

Step 3: Render the iframe from a server component

The clean App Router pattern: a server component fetches the embed URL directly (no HTTP hop through your own API), then passes it as a prop to a small client component that owns the iframe and its resize logic.

// app/(app)/dashboard/page.tsx  (server component by default)
import { DashboardFrame } from "./dashboard-frame";

export const dynamic = "force-dynamic"; // never cache a tenant-specific URL

export default async function DashboardPage() {
  const session = await getSession(); // runs on the server
  if (!session?.user) redirect("/login");

  const tenantId = await lookupTenantForUser(session.user.id);
  const url = await mintEmbedUrl(tenantId); // same signing code, called directly

  return <DashboardFrame src={url} />;
}
// app/(app)/dashboard/dashboard-frame.tsx
"use client";
import { useState } from "react";

export function DashboardFrame({ src }: { src: string }) {
  const [loaded, setLoaded] = useState(false);
  return (
    <iframe
      src={src}
      title="Your analytics dashboard"
      onLoad={() => setLoaded(true)}
      loading="lazy"
      style={{
        width: "100%",
        height: "85vh",
        border: 0,
        borderRadius: 8,
        opacity: loaded ? 1 : 0,
        transition: "opacity 200ms",
      }}
    />
  );
}

Why a server component fetches the URL yourself instead of calling your own route handler from the client: fewer network hops, no client-side token state to manage, and the signed URL arrives in the initial HTML. The route handler from step 2 stays useful for SPA-style pages and mobile clients; both paths share one signing function.

Step 4: Fix hydration and sizing

The classic Next.js iframe bug is the hydration mismatch: a component that measures window.innerHeight during SSR renders a different height than on the client, and React patches it with a console warning. The fix is to keep layout math CSS-only where possible (viewport units, flex/grid) and confine JS measurement to a client boundary. Client components are the documented escape hatch for browser APIs in App Router; the Next.js docs on client components cover the rules.

For responsive sizing, viewport-relative heights beat fixed pixels on every device class:

  • Desktop app shell: height: calc(100vh - headerHeight) so the frame fills the content area without double scrollbars.
  • Mobile: let the iframe grow with content where the provider supports a resize postmessage; otherwise stack charts vertically at full width.
  • Loading state: fade in on onLoad so the frame never flashes empty inside your layout.

One more App Router detail: mark dashboard pages dynamic (force-dynamic above). A statically cached page would serve one tenant’s signed URL to everyone, which is exactly the leak you are trying to prevent.

Step 5: Route protection and metadata

Protect the dashboard route with middleware so unauthenticated visitors never reach the frame:

// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(req: NextRequest) {
  const session = req.cookies.get("session");
  if (!session) return NextResponse.redirect(new URL("/login", req.url));
  return NextResponse.next();
}

export const config = { matcher: ["/dashboard/:path*"] };

Middleware is a convenience layer, not the security boundary. The route handler in step 2 checks the session again, and the analytics platform verifies the token. Three checks, each independently sufficient: that is defense in depth, and it matches the API security guidance in the OWASP API Security Top 10 (auth failures on object-level access are the #1 listed risk).

Add metadata so the shell page presents correctly when shared:

// app/(app)/dashboard/page.tsx
import type { Metadata } from "next";

export const metadata: Metadata = {
  title: "Analytics | Your App",
  robots: { index: false }, // customer dashboards should not be indexed
};

Common Next.js embed mistakes

  • Signing the token in a client component. The secret ships in the JS bundle. Mint server-side, always.
  • Taking tenant ID from the URL. /dashboard?tenant_id=other-corp is an invitation. Resolve tenant from the session server-side.
  • Caching a signed page. Static generation bakes one tenant’s token into shared HTML. Use dynamic rendering for anything with a token in the URL.
  • Long-lived tokens “for convenience.” A 30-day embed token is a stored XSS waiting to happen. Ten minutes covers a dashboard session fine; refresh by re-fetching.
  • Trusting middleware alone. Middleware checks cookies for speed; the route handler and the platform check authority. All three, not one.

Where Embedful fits

If you want the dashboard layer off your roadmap, Embedful handles the pieces this guide treats as manual work: dashboards built on direct PostgreSQL/MySQL/Firebase connections, Pro plan and up; API data sources from the Starter plan; tenant parameters verified against signed JWT tokens; white-label branding; and customer-facing dashboards on Pro (25 dashboards) and Agency (100), with unlimited viewers per dashboard. The embed itself is the same iframe pattern from step 3: your Next.js route handler mints the token, Embedful verifies it.

To ship one tenant-scoped dashboard inside a Next.js app today: create an Embedful account, connect a data source, and paste the embed URL into the frame component from step 3. The token minting code above works unchanged against it.

Frequently asked questions

Does embedding a dashboard in Next.js need a client component?

The iframe element itself can render from a server component, but interactive behavior (resize handling, loading states, postmessage listeners) requires a "use client" boundary. The common shape: server component fetches the signed URL, tiny client component owns the frame.

Can I embed without JWTs?

You can embed with a plain tenant query parameter for internal tools, and it is fine until customers are involved. For customer-facing dashboards, an unauthenticated tenant parameter is trivially editable; use signed tokens, as covered in the JWT guide.

Does the iframe hurt my app’s performance?

An iframe loads its own document, so cost scales with what the dashboard itself ships: charts, data queries, fonts. Keep tokens short, use loading="lazy", and put dashboards on their own route so the rest of your app never pays for them.

Will Next.js Server Actions work for token minting?

Yes. A server action can sign the token just like a route handler; the route handler is preferable when non-browser clients (mobile apps, scripts) need the same endpoint.

What about Pages Router instead of App Router?

The architecture is identical: mint in getServerSideProps or an API route under pages/api/, render the iframe in a page. App Router just makes the server/client boundary explicit, which removes most accidental secret leaks.

Sources


Related Articles