How to Embed Superset Dashboards in External Applications Using the Embedded SDK
The Superset Embedded SDK renders dashboards inside isolated iframes using short-lived Guest Tokens for authentication, enabling secure integration into any web application.
The Apache Superset Embedded SDK provides a production-ready solution to embed Superset dashboards and charts into external React, Vue, or plain JavaScript applications. By leveraging Guest Token authentication and cross-origin iframe sandboxing, the SDK ensures embedded analytics remain secure while offering extensive UI customization options. This guide walks through the complete implementation using source code from the apache/superset repository.
Prerequisites: Enable Embedded Mode
Before embedding, the Superset backend must explicitly allow embedding via configuration.
The EMBEDDED_SUPERSET feature flag must be set to True in superset/config.py. Additionally, each dashboard requires an embed configuration record (stored in superset/models/embedded_dashboard.py) that registers allowed parent domains. Without these backend settings, the SDK’s iframe requests will be rejected with a 403 error.
How the Superset Embedded SDK Works
Guest Token Authentication
Authentication relies on Guest Tokens—short-lived JWTs created by calling the POST /api/v1/security/guest_token endpoint. These tokens grant scoped access to specific resources (dashboards or charts) and can include Row-Level Security (RLS) clauses for data filtering. The SDK receives these tokens via the fetchGuestToken callback you provide.
In superset-embedded-sdk/src/guestTokenRefresh.ts, the SDK decodes the JWT’s exp claim using jwt-decode, calculates the remaining time-to-live, and schedules an automatic refresh before expiration. This ensures uninterrupted user sessions without manual token management.
Iframe Sandboxing and Security
The SDK creates a restricted iframe element with sandbox attributes defined in superset-embedded-sdk/src/index.ts. By default, it applies:
allow-same-originallow-scriptsallow-presentationallow-downloadsallow-formsallow-popups
You can extend these permissions via the iframeSandboxExtras parameter. For browser features like clipboard access or fullscreen mode, pass additional policies through iframeAllowExtras, which the SDK appends to the iframe’s allow attribute.
Cross-Window Communication
The SDK establishes a two-way RPC channel between the host page and the Superset iframe using the Switchboard library and a MessageChannel. This channel, initialized in embedDashboard (lines 107-124 of src/index.ts), transmits the guest token to the iframe and receives events such as data mask updates from dashboard filters. The host application can also invoke iframe-side methods like setThemeConfig through this channel.
Step-by-Step Implementation
Install the SDK
Add the package via npm or load it from a CDN:
npm install --save @superset-ui/embedded-sdk
For CDN usage:
<script src="https://unpkg.com/@superset-ui/embedded-sdk"></script>
Basic Dashboard Embed
Import embedDashboard from superset-embedded-sdk/src/index.ts and mount the iframe to a DOM element:
import { embedDashboard } from '@superset-ui/embedded-sdk';
async function fetchGuestToken(): Promise<string> {
const resp = await fetch('/api/guest-token');
const { token } = await resp.json();
return token;
}
const container = document.getElementById('superset-container');
embedDashboard({
id: 'abc123', // Dashboard UUID from Superset UI
supersetDomain: 'https://superset.example.com',
mountPoint: container,
fetchGuestToken,
dashboardUiConfig: {
hideTitle: true,
filters: { expanded: true, visible: true },
},
});
The dashboardUiConfig object translates to URL parameters via the calculateConfig function. It maps options like hideTitle and filter visibility to the DASHBOARD_UI_FILTER_CONFIG_URL_PARAM_KEY query parameter, which Superset parses on load to adjust the UI layout.
Listen to Dashboard Events
After embedding, you can observe filter changes and other data mask updates:
const dashboard = await embedDashboard({ /* ... */ });
dashboard.observeDataMask((mask) => {
console.log('Filter selection changed:', mask);
});
Advanced Configuration
Custom Sandbox Permissions
To allow top-level navigation or popup escapes, extend the sandbox attributes:
embedDashboard({
id: 'abc123',
supersetDomain: 'https://superset.example.com',
mountPoint: document.getElementById('embed'),
fetchGuestToken,
iframeSandboxExtras: ['allow-top-navigation', 'allow-popups-to-escape-sandbox'],
iframeAllowExtras: ['clipboard-write', 'fullscreen'],
});
This modifies the iframe creation logic in src/index.ts (lines 90-97) where iframe.sandbox.add() applies your additional tokens.
Control Referrer Policy
When Superset validates embedding domains via the Referer header, you may need to constrain the policy:
embedDashboard({
/* ... */
referrerPolicy: 'same-origin',
});
The SDK sets iframe.referrerPolicy directly (lines 100-104 of src/index.ts), ensuring the browser sends the appropriate header with the initial iframe request.
Custom Permalink Handling
Override Superset’s native share URLs by providing a resolvePermalinkUrl callback. The SDK registers this method on the Switchboard channel (lines 60-76 of src/index.ts), allowing you to rewrite internal permalinks to your application’s routing scheme:
embedDashboard({
/* ... */
resolvePermalinkUrl: ({ key }) => {
return `https://my-app.com/analytics/share/${key}`;
},
});
Backend Guest Token Generation
Your backend must generate Guest Tokens by authenticating to Superset’s REST API. Here is a Python implementation:
import requests
SUPERSET_URL = 'https://superset.example.com'
ADMIN_JWT = 'your_admin_token' # Obtained via /api/v1/security/login
payload = {
"user": {"username": "embedded_user", "first_name": "Guest"},
"resources": [{"type": "dashboard", "id": "abc123"}],
"rls": [{"clause": "region = 'North America'"}] # Optional RLS filtering
}
response = requests.post(
f'{SUPERSET_URL}/api/v1/security/guest_token',
json=payload,
headers={'Authorization': f'Bearer {ADMIN_JWT}'}
)
guest_token = response.json()['token']
This token is then consumed by the SDK’s fetchGuestToken function. The RLS clauses ensure embedded users see only data subsets defined by your security rules.
Summary
- Enable the feature flag: Set
EMBEDDED_SUPERSET = Trueinsuperset/config.pyand configure allowed domains in the dashboard embed settings. - Use Guest Tokens: Implement a backend endpoint that calls
POST /api/v1/security/guest_tokento generate scoped, short-lived JWTs for authentication. - Mount with
embedDashboard: Import from@superset-ui/embedded-sdk, provide the dashboard UUID, Superset domain, and token fetcher to render the iframe. - Configure security: Adjust
iframeSandboxExtrasandiframeAllowExtrasfor specific browser capabilities, and setreferrerPolicyto match your domain validation strategy. - Handle lifecycle: The SDK automatically refreshes tokens before expiration using logic from
guestTokenRefresh.ts, preventing session timeouts. - Customize URLs: Provide
resolvePermalinkUrlto rewrite share links for seamless integration with your host application’s navigation.
Frequently Asked Questions
What is a Guest Token in Superset embedding?
A Guest Token is a short-lived JWT generated by the Superset backend at POST /api/v1/security/guest_token. It authorizes an anonymous or embedded user to view specific dashboards or charts without requiring a full Superset login. The token contains claims for the user identity, resource IDs, and optional Row-Level Security (RLS) filters, and typically expires within minutes to minimize security exposure.
How does the SDK automatically refresh authentication tokens?
The SDK decodes the JWT’s exp claim using the jwt-decode library and schedules a refresh using setTimeout before the token expires. Implemented in superset-embedded-sdk/src/guestTokenRefresh.ts, this logic subtracts a safety buffer from the remaining TTL and invokes your fetchGuestToken callback to obtain a new token, ensuring the embedded dashboard remains active without user interruption.
Can I hide specific UI elements like the filter panel or title bar?
Yes. Pass a dashboardUiConfig object to embedDashboard with properties like hideTitle: true or filters: { expanded: false, visible: false }. The SDK encodes these options into URL parameters using the calculateConfig function in src/index.ts, which Superset’s frontend interprets to conditionally render UI components when the iframe loads.
What security risks does the iframe sandbox mitigate?
The default sandbox attributes (allow-same-origin, allow-scripts, etc.) prevent the embedded Superset instance from accessing the parent window’s DOM, cookies, or storage, protecting against XSS and clickjacking attacks. You can relax these restrictions via iframeSandboxExtras if your use case requires specific capabilities like top-level navigation, though this increases the attack surface and should be done cautiously according to the implementation in src/index.ts lines 90-97.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →