This guide walks you through everything you need to embed DataBrain dashboards in a production environment with proper authentication, security, and customization.

Prerequisites

DataBrain Account

Data Source

Connected database or data warehouse

Backend Server

For secure token generation

Frontend App

React, Vue, Angular, or vanilla JS

Architecture Overview

Here’s how the embedding architecture works:
1

User Login

End user logs into your application
2

Request Token

Your frontend requests a guest token from your backend
3

Generate Token

Your backend calls DataBrain API to generate a guest token
POST https://api.usedatabrain.com/api/v2/guest-token/create
4

Return Token

DataBrain API returns guest token to your backend, which passes it to frontend
5

Embed Component

Frontend passes token to the dbn-dashboard web component
<dbn-dashboard token="guest-token" dashboard-id="dashboard-id" />
6

Fetch Dashboard

Component fetches dashboard data from DataBrain using the guest token
7

Render

Dashboard renders with user-specific data and permissions
Flow Diagram:
┌─────────┐     ┌──────────┐     ┌─────────┐     ┌──────────┐
│End User │────>│ Your App │────>│Your API │────>│DataBrain │
└─────────┘     └──────────┘     └─────────┘     │   API    │
    Login        Request Token   Generate Token   └──────────┘


                                                    Guest Token

┌─────────┐     ┌──────────┐     ┌─────────┐          │
│Dashboard│<────│Component │<────│Your App │<─────────┘
│  Data   │     │ Renders  │     │Gets Token│
└─────────┘     └──────────┘     └─────────┘

Step 1: Create Workspace & Dashboard

1.1 Create a Workspace

1

Navigate to Workspaces

Go to the DataBrain platform and click “Create Workspace”
2

Configure Workspace

  • Enter workspace name
  • Select workspace type (standard or private)
  • Configure initial settings

Create Workspace Guide

Detailed workspace creation guide

1.2 Connect Data Source

1

Add Data Source

Click “Add Data Source” in your workspace
2

Select Database Type

Choose from 18+ supported databases
3

Enter Credentials

Provide connection details (host, port, credentials)
4

Test Connection

Verify the connection works
5

Configure Tenancy

Set up multi-tenancy if needed

Data Sources Guide

Connect your database

1.3 Create Dashboard

1

Create Dashboard

Click “New Dashboard” in your workspace
2

Add Metrics

Create charts, tables, and KPIs using the visual builder
3

Add Filters

Configure dashboard-level filters for interactivity
4

Customize Layout

Arrange metrics and adjust sizing
5

Save Dashboard

Save and note your dashboard ID

Create Dashboard Guide

Build your first dashboard

Step 2: Create Data App

A Data App packages your dashboards for embedding with security and configuration.

2.1 Navigate to Data Apps

Go to Data → Data Apps in your workspace

2.2 Create New Data App

1

Click New Data App

Start creating a new Data App
2

Configure Basic Settings

{
  "name": "customer-analytics-app",
  "description": "Analytics for customer portal",
  "workspace": "your-workspace-name"
}
3

Select Dashboards

Choose which dashboards to include in this Data App
4

Configure Settings

  • Set default permissions
  • Configure multi-tenancy
  • Set token expiry defaults
5

Save and Get API Token

Copy your API token - you’ll need this for generating guest tokens
Store your API token securely! Never commit it to version control or expose it in frontend code. Use environment variables.

2.3 Find Your Dashboard ID

1

Open Data App

Navigate to your Data App
2

Find Dashboard Section

Look for the dashboards list
3

Copy Dashboard ID

Each dashboard has a unique ID (e.g., sales-dashboard-2024)

Finding Dashboard IDs

Detailed guide on locating IDs

Step 3: Backend Integration

Set up your backend to generate guest tokens securely.

3.1 Store API Token

Add your DataBrain API token to environment variables:
DATABRAIN_API_TOKEN=dbn_live_abc123...
DATABRAIN_API_URL=https://api.usedatabrain.com
DATA_APP_NAME=customer-analytics-app

3.2 Implement Token Generation

Create an API endpoint to generate guest tokens:
// routes/databrain.js
const express = require('express');
const router = express.Router();

router.post('/guest-token', async (req, res) => {
  try {
    const { userId } = req.user; // From your auth middleware
    
    const response = await fetch(
      `${process.env.DATABRAIN_API_URL}/api/v2/guest-token/create`,
      {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${process.env.DATABRAIN_API_TOKEN}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          clientId: userId,
          dataAppName: process.env.DATA_APP_NAME,
          expiryTime: 3600000 // 1 hour
        })
      }
    );
    
    const data = await response.json();
    
    if (!response.ok) {
      throw new Error(data.error?.message || 'Failed to generate token');
    }
    
    res.json({ token: data.token });
  } catch (error) {
    console.error('Token generation error:', error);
    res.status(500).json({ error: 'Failed to generate token' });
  }
});

module.exports = router;

3.3 Advanced Token Configuration

Add Row-Level Security (RLS) and filters:
// With RLS and app filters
const tokenRequest = {
  clientId: userId,
  dataAppName: process.env.DATA_APP_NAME,
  params: {
    // Row-level security
    rlsSettings: [{
      metricId: 'sales-metric',
      values: {
        customer_id: userCustomerId,
        region: userRegion
      }
    }],
    // Dashboard app filters
    dashboardAppFilters: [{
      dashboardId: 'sales-dashboard',
      values: {
        date_range: {
          startDate: '2024-01-01',
          endDate: '2024-12-31'
        },
        region: userRegion
      },
      isShowOnUrl: false
    }]
  },
  // Permissions
  permissions: {
    isEnableDownloadMetrics: true,
    isEnableUnderlyingData: false,
    isEnableManageMetrics: false
  },
  expiryTime: 3600000
};

Token Body Reference

Complete token configuration options

Step 4: Frontend Integration

4.1 Install Package

npm install @databrainhq/plugin

4.2 Create Dashboard Component

import { useEffect, useState } from 'react';
import '@databrainhq/plugin/web';

function AnalyticsDashboard() {
  const [token, setToken] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchToken() {
      try {
        const response = await fetch('/api/databrain/guest-token', {
          method: 'POST',
          credentials: 'include' // Include auth cookies
        });
        
        if (!response.ok) {
          throw new Error('Failed to fetch token');
        }
        
        const data = await response.json();
        setToken(data.token);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    }

    fetchToken();
  }, []);

  if (loading) {
    return <div>Loading dashboard...</div>;
  }

  if (error) {
    return <div>Error loading dashboard: {error}</div>;
  }

  return (
    <div className="dashboard-container">
      <dbn-dashboard 
        token={token}
        dashboard-id="sales-dashboard"
        enable-download-csv
        enable-download-all-metrics
      />
    </div>
  );
}

export default AnalyticsDashboard;

4.3 Add Customization

<dbn-dashboard 
  token={token}
  dashboard-id="sales-dashboard"
  // Downloads
  enable-download-csv
  enable-download-all-metrics
  // UI Options
  is-hide-chart-settings={false}
  options-icon="download"
  // Custom messages
  custom-messages={JSON.stringify({
    tokenExpiry: "Your session expired. Please refresh the page.",
    tokenAbsent: "Unable to load dashboard. Please try again."
  })}
  // Theme
  theme={JSON.stringify({
    general: {
      primaryColor: '#0066CC',
      backgroundColor: '#FFFFFF',
      fontFamily: 'Inter, system-ui, sans-serif'
    },
    chart: {
      colors: ['#0066CC', '#00C2B8', '#FF6B6B', '#4ECDC4']
    }
  })}
  // Event handler
  handle-server-event="handleDashboardEvents"
/>

Component Options

All customization options

Step 5: Testing & Deployment

5.1 Test Locally

1

Start Backend

Ensure your backend token endpoint is running
2

Start Frontend

Run your frontend development server
3

Verify Dashboard Loads

Check that the dashboard renders correctly
4

Test Interactions

  • Click on charts
  • Apply filters
  • Download CSV
  • Test responsive behavior

5.2 Environment Variables

Set up environment variables for each environment:
DATABRAIN_API_TOKEN=dbn_test_...
DATABRAIN_API_URL=https://api.usedatabrain.com
DATA_APP_NAME=my-app-dev

5.3 Deploy

Deploy both backend and frontend to your hosting platform:
  • Vercel, Netlify (Frontend)
  • AWS, GCP, Azure (Backend)
  • Heroku, Railway, Render (Full-stack)

Next Steps