Skip to Content

Component Options

Load dashboard data without the UI

Get a dashboard's details and metric list with a guest token, and draw them with your own React components.

@databrainhq/plugin/data loads a dashboard’s details and its metric definitions. It draws nothing and does not load the Databrain chart engine. It is about 1.3 KB gzip.

When to use it

Use it when you build your own screen from a dashboard’s setup. For example, a list of the dashboard’s metrics, their names and chart types, in your own components and your own styles.

Do not use it to get the numbers behind a chart. The response holds metric definitions, not query results. If you want Databrain to draw the charts, use <dbn-dashboard> or <dbn-metric>. See Embed a dashboard.

Before you start

  • You have a guest token from your backend. See Guest token body.
  • You have the dashboard id from the Embeds page.
  • Your page’s domain is in the data app’s whitelisted domains. See Whitelist domains.
  • For useDashboardData and DashboardData, your app uses React 18 or 19.

Steps

  1. Install the package:

    npm install @databrainhq/plugin
  2. Import from the data subpath. The response items are loosely typed, so describe the fields you read:

    import { useDashboardData } from '@databrainhq/plugin/data';
    
    type MetricCard = {
      externalMetricId: string;
      externalMetric?: { name?: string; chartOptions?: { chartType?: string } };
    };
    
    export function MetricNames({
      token,
      dashboardId,
    }: {
      token: string;
      dashboardId: string;
    }) {
      const { data, error, isLoading, refetch } = useDashboardData({
        token,
        dashboardId,
      });
      if (isLoading) return <p>Loading</p>;
      if (error) return <button onClick={refetch}>{error.message}</button>;
      const cards = (data?.externalMetrics ?? []) as MetricCard[];
      return (
        <ul>
          {cards.map((card) => (
            <li key={card.externalMetricId}>
              {card.externalMetric?.name} ({card.externalMetric?.chartOptions?.chartType})
            </li>
          ))}
        </ul>
      );
    }

    You see the dashboard’s metric names in your own component.

    Example host page with a plain list titled Metrics on this dashboard: Seats sold, Revenue by plan, Monthly revenue and Revenue by region, each with its chart type
    Your own markup, filled from the dashboard's metric definitions. No chart engine loads.
  3. Outside React, call fetchDashboardData. It returns a promise. When Databrain answers with an error, it throws a DashboardDataError. A network failure or an abort rejects with the browser’s own error:

    import { DashboardDataError, fetchDashboardData } from '@databrainhq/plugin/data';
    
    const controller = new AbortController();
    
    try {
      const data = await fetchDashboardData({
        token: guestToken,
        dashboardId,
        signal: controller.signal,
      });
      console.log(data.externalDashboard?.name, data.externalMetrics?.length);
    } catch (err) {
      if (err instanceof DashboardDataError) {
        console.error(err.status, err.code, err.message);
      } else {
        throw err;
      }
    }

The three exports

ExportUse it for
useDashboardData(options)A React hook. Returns { data, error, status, isLoading, refetch }.
<DashboardData {...options}>{(result) => ...}</DashboardData>The same result as a render prop.
fetchDashboardData(options)A plain promise, for code outside React. Takes an optional signal (AbortSignal).

Options

OptionTypeDefaultWhat it does
tokenstringrequiredThe guest token. With no token, the hook stays idle.
dashboardIdstringnoneThe dashboard id. Leave it out only when the guest token names one dashboard.
configIdstringnoneData app configuration id.
isEnbooleannoneSet true to request encrypted appFilters and dashboardAppFilters. Omit this option for unencrypted values. Passing false also requests encryption.
baseUrlstringhttps://api.usedatabrain.comBackend origin, for example a self-hosted one.
enabledbooleantruefalse keeps the hook idle. Hook and component only.

The hook loads again when an option changes, and cancels the old request. refetch() loads again with the same options.

What you get back

FieldTypeWhat it holds
dataobject or nullThe /api/v2/dashboard response.
data.externalDashboardobjectThe dashboard. Typed fields id, externalDashboardId and name; other fields can be present.
data.externalMetricsarrayOne item per card: externalMetricId, externalDashboardId and externalMetric. externalMetric holds the definition, for example name, metricId and chartOptions.chartType.
statusstringidle, loading, success or error.
isLoadingbooleantrue while status is loading.
errorDashboardDataError or nullmessage, status (HTTP status) and code from the server. For a network failure, status and code are empty.

The response holds metric definitions, not query results. To show the numbers, use <dbn-dashboard> or <dbn-metric>.

Keep the token safe

  • Create the guest token on your server, with your data app API key. Never create it in the browser.
  • Send the browser only the finished guest token.
  • The token carries the same tenant and access limits as an embed. The data you get is the data that tenant is allowed to see.
  • The token goes in the X-Plugin-Token header, not in the URL, so it stays out of logs and browser history.
  • Do not log or forward the whole response. It can hold the guest token and your app filter values.

See Guest token body.

Package size

The data subpath is about 2.7 KB raw and 1.3 KB gzip. It imports only react, so your bundle does not pick up the chart engine.

How the request is sent

GET <baseUrl>/api/v2/dashboard?dashboardId=<id> with these headers:

HeaderValue
X-Plugin-TokenThe guest token. It is never put in the URL.
X-Plugin-OriginYour page’s host.
X-Dbn-Plugin-VersionThe plugin build.
X-Dbn-Plugin-ContractThe plugin contract number.

If you send requests through your own proxy, let all four headers through.

If something goes wrong

  • error.status is 401 or 403. The guest token is expired or wrong, or your page’s domain is not whitelisted. Create a new token, then check the whitelisted domains.
  • Databrain returned an invalid response. baseUrl does not point at a Databrain backend.

Next: Embed a dashboard.