Framework Integration
Embed in Svelte
Show a Databrain dashboard or metric in a Svelte 5 or SvelteKit app.
Before you start
- Your backend returns a guest token at
/api/databrain-token. Create a guest token - You have a dashboard id. Find the dashboard id
Steps
- Install the plugin.
npm install @databrainhq/plugin- Add a component, for example
src/lib/Dashboard.svelte. It imports the plugin inonMount, so it also works with SvelteKit server rendering.
<script lang="ts">
import { onMount } from 'svelte';
let { dashboardId }: { dashboardId: string } = $props();
let ready = $state(false);
let token = $state<string>();
let el = $state<HTMLElement & { handleServerEvent?: (...args: unknown[]) => unknown }>();
onMount(async () => {
await import('@databrainhq/plugin/web');
const res = await fetch('/api/databrain-token');
token = (await res.json()).token;
ready = true;
});
$effect(() => {
if (el) el.handleServerEvent = (event) => console.log(event);
});
</script>
{#if ready && token}
{#key dashboardId}
<dbn-dashboard
bind:this={el}
{token}
dashboard-id={dashboardId}
enable-download-csv="true"
options={{ disableMetricCreation: true, hideDashboardName: true }}
></dbn-dashboard>
{/key}
{/if}- Use it on a page.
<script lang="ts">
import Dashboard from '$lib/Dashboard.svelte';
</script>
<Dashboard dashboardId="your-dashboard-id" />You see the dashboard on the page.
Show one metric
<dbn-metric {token} metric-id={metricId}></dbn-metric>Render it inside the same {#if ready && token} block. Find the metric id
How the props work
- Strings and booleans go in the markup as kebab-case attributes. Write booleans as
"true". - Svelte sets an object, such as
options, as a property on the element. - Functions go on the element through
bind:this. Assign an inline arrow function. Do not pass functions in the markup. {#key dashboardId}remounts the element when the dashboard changes.
If something goes wrong
customElements is not definedin SvelteKit. You imported the plugin at the top of a<script>. Import it insideonMount.- The embed shows the first dashboard of the data app, not yours. Write the attribute as
dashboard-id, in kebab case. Use the id, not the dashboard name. handleServerEventnever runs. Assign an inline arrow function. The element drops a named function.