> ## Documentation Index
> Fetch the complete documentation index at: https://docs.usedatabrain.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 5-Minute Embedding Tutorial

> Get your first DataBrain dashboard embedded in 5 minutes

<Note>
  This tutorial will get you up and running with a working embedded dashboard in just 5 minutes. We'll use a sample token and dashboard so you can see results immediately.
</Note>

## What You'll Build

By the end of this tutorial, you'll have:

* ✅ A working embedded DataBrain dashboard
* ✅ Understanding of the core embedding concepts
* ✅ A foundation to build upon for production

## Prerequisites

* Node.js 14+ installed
* A React, Vue, or vanilla JavaScript project
* 5 minutes of your time ⏱️

## Step 1: Install the Package

<CodeGroup>
  ```bash npm theme={"dark"}
  npm install @databrainhq/plugin
  ```

  ```bash yarn theme={"dark"}
  yarn add @databrainhq/plugin
  ```

  ```bash pnpm theme={"dark"}
  pnpm add @databrainhq/plugin
  ```
</CodeGroup>

## Step 2: Import the Plugin

Add this import to your component or main file:

<CodeGroup>
  ```javascript React theme={"dark"}
  import '@databrainhq/plugin/web';

  function Dashboard() {
    return (
      <dbn-dashboard 
        token="3affda8b-7bd4-4a88-9687-105a94cfffab" 
        dashboard-id="ex-demo" 
      />
    );
  }

  export default Dashboard;
  ```

  ```javascript Vue theme={"dark"}
  <template>
    <dbn-dashboard 
      token="3affda8b-7bd4-4a88-9687-105a94cfffab" 
      dashboard-id="ex-demo" 
    />
  </template>

  <script>
  import '@databrainhq/plugin/web';

  export default {
    name: 'Dashboard'
  }
  </script>
  ```

  ```javascript Vanilla JS theme={"dark"}
  import '@databrainhq/plugin/web';

  // In your HTML
  document.body.innerHTML = `
    <dbn-dashboard 
      token="3affda8b-7bd4-4a88-9687-105a94cfffab" 
      dashboard-id="ex-demo"
    />
  `;
  ```

  ```html HTML theme={"dark"}
  <!DOCTYPE html>
  <html>
  <head>
    <script type="module">
      import '@databrainhq/plugin/web';
    </script>
  </head>
  <body>
    <dbn-dashboard 
      token="3affda8b-7bd4-4a88-9687-105a94cfffab" 
      dashboard-id="ex-demo"
    />
  </body>
  </html>
  ```
</CodeGroup>

## Step 3: Run and View

Start your development server and you should see the sample dashboard! 🎉

```bash theme={"dark"}
npm run dev
# or
npm start
```

<Check>
  **Congratulations!** You've embedded your first DataBrain dashboard. The dashboard you're seeing is a sample with demo data.
</Check>

## Understanding What You Built

Let's break down the code:

### The Component

```html theme={"dark"}
<dbn-dashboard token="..." dashboard-id="..." />
```

### The Token

```
token="3affda8b-7bd4-4a88-9687-105a94cfffab"
```

This is a **guest token** - a temporary access token that allows viewing the dashboard. In production, you'll generate these from your backend.

### The Dashboard ID

```
dashboard-id="ex-demo"
```

This identifies which dashboard to display. Each dashboard in DataBrain has a unique ID.

## Next: Make It Production-Ready

The sample above works great for testing, but for production you need to:

### 1. Create Your Own Dashboard

1. **Create your own dashboard** at [app.usedatabrain.com](https://app.usedatabrain.com/users/sign-up)
2. **Connect your database** as a data source
3. **Build your metrics and dashboards**
4. **Create a Data App** for embedding
5. **Generate tokens from your backend** (see below)

<Card title="Complete Setup Guide" icon="book" href="/developer-docs/how-to-embed">
  Follow the full setup process
</Card>

### 2. Generate Tokens from Your Backend

<Warning>
  **Security First:** Never expose your API token in frontend code. Always generate guest tokens from your backend.
</Warning>

Here's how token generation works:

**Token Flow:**

```
1. User accesses dashboard
   ↓
2. Frontend → Backend (request guest token)
   ↓
3. Backend → DataBrain API (POST /guest-token/create)
   ↓
4. DataBrain API → Backend (return guest token)
   ↓
5. Backend → Frontend (return guest token)
   ↓
6. Frontend → Dashboard component (render with token)
```

#### Backend Example (Node.js)

```javascript theme={"dark"}
// backend/api/get-token.js
import fetch from 'node-fetch';

export async function getGuestToken(userId) {
  const response = await fetch(
    'https://api.usedatabrain.com/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: 'your-data-app-name'
      })
    }
  );
  
  const data = await response.json();
  return data.token;
}
```

#### Frontend Example (React)

```javascript theme={"dark"}
import { useEffect, useState } from 'react';
import '@databrainhq/plugin/web';

function Dashboard({ userId }) {
  const [token, setToken] = useState(null);

  useEffect(() => {
    // Fetch token from YOUR backend
    fetch('/api/get-databrain-token', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userId })
    })
      .then(res => res.json())
      .then(data => setToken(data.token));
  }, [userId]);

  if (!token) return <div>Loading...</div>;

  return (
    <dbn-dashboard 
      token={token} 
      dashboard-id="your-dashboard-id" 
    />
  );
}
```

<Card title="Guest Token API" icon="key" href="/developer-docs/helpers/api-reference/token">
  Complete token generation API docs
</Card>

### 3. Customize the Dashboard

Add options to customize appearance and behavior:

```html theme={"dark"}
<dbn-dashboard 
  token={token}
  dashboard-id="your-dashboard-id"
  enable-download-csv
  enable-email-csv
  custom-messages={JSON.stringify({
    tokenExpiry: "Your session has expired. Please refresh.",
  })}
  theme={JSON.stringify({
    general: {
      primaryColor: '#0066CC',
      backgroundColor: '#FFFFFF'
    }
  })}
/>
```

<Card title="Component Options" icon="sliders" href="/developer-docs/helpers/options">
  Explore all customization options
</Card>

## Embed a Single Metric

You can also embed individual metrics instead of full dashboards:

```html theme={"dark"}
<dbn-metric 
  token={token}
  metric-id="your-metric-id"
/>
```

## Common Customizations

<Tabs>
  <Tab title="Hide Elements">
    ```html theme={"dark"}
    <dbn-dashboard 
      token={token}
      dashboard-id="dashboard-id"
      is-hide-chart-settings
      is-hide-table-preview
    />
    ```
  </Tab>

  <Tab title="Enable Downloads">
    ```html theme={"dark"}
    <dbn-dashboard 
      token={token}
      dashboard-id="dashboard-id"
      enable-download-csv
      enable-download-all-metrics
    />
    ```
  </Tab>

  <Tab title="Custom Theme">
    ```javascript theme={"dark"}
    const theme = {
      general: {
        primaryColor: '#FF6B6B',
        backgroundColor: '#F8F9FA',
        fontFamily: 'Inter'
      },
      chart: {
        colors: ['#FF6B6B', '#4ECDC4', '#45B7D1']
      }
    };

    <dbn-dashboard 
      token={token}
      dashboard-id="dashboard-id"
      theme={JSON.stringify(theme)}
    />
    ```
  </Tab>

  <Tab title="Event Handlers">
    ```javascript theme={"dark"}
    // Define global handler
    window.handleDashboardEvent = (event) => {
      console.log('Dashboard event:', event);
    };

    <dbn-dashboard 
      token={token}
      dashboard-id="dashboard-id"
      handle-server-event="handleDashboardEvent"
    />
    ```
  </Tab>
</Tabs>

## Framework-Specific Guides

Get detailed integration guides for your framework:

<CardGroup cols={3}>
  <Card title="React" icon="react" href="/developer-docs/framework-specific-guide/reactjs">
    React integration guide
  </Card>

  <Card title="Next.js" icon="n" href="/developer-docs/framework-specific-guide/nextjs">
    Next.js with SSR support
  </Card>

  <Card title="Vue" icon="vuejs" href="/developer-docs/framework-specific-guide/vuejs">
    Vue 3 integration
  </Card>

  <Card title="Angular" icon="angular" href="/developer-docs/framework-specific-guide/angular">
    Angular setup guide
  </Card>

  <Card title="Svelte" icon="s" href="/developer-docs/framework-specific-guide/svelte">
    Svelte integration
  </Card>

  <Card title="Vanilla JS" icon="js" href="/developer-docs/framework-specific-guide/vanillajs">
    Plain JavaScript
  </Card>
</CardGroup>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Dashboard not rendering" icon="triangle-exclamation">
    **Check:**

    * Plugin is imported before component renders
    * Token is valid and not expired
    * Dashboard ID is correct
    * No console errors
  </Accordion>

  <Accordion title="Token expired error" icon="clock">
    **Solution:** Generate a fresh token from your backend. Guest tokens can be set to expire after a certain time.
  </Accordion>

  <Accordion title="CORS errors" icon="shield">
    **Fix:** Ensure your domain is whitelisted in the Data App settings. Or generate tokens from your backend instead of frontend.
  </Accordion>

  <Accordion title="Styling issues" icon="palette">
    **Try:**

    * Check for CSS conflicts
    * Use custom theme options
    * Wrap in a container div
    * Check z-index values
  </Accordion>
</AccordionGroup>

<Card title="Troubleshooting Guide" icon="wrench" href="/developer-docs/testing/troubleshooting">
  Complete troubleshooting reference
</Card>

## What's Next?

You've successfully embedded a DataBrain dashboard! Here's what to explore next:

<CardGroup cols={2}>
  <Card title="Complete Setup" icon="list-check" href="/developer-docs/embedding-setup/step-by-step-guide">
    Production-ready setup guide
  </Card>

  <Card title="Security & Auth" icon="shield" href="/developer-docs/multi-tenant-access-control">
    Multi-tenancy and access control
  </Card>

  <Card title="Customization" icon="palette" href="/developer-docs/helpers/options">
    Advanced customization options
  </Card>

  <Card title="API Reference" icon="book" href="/developer-docs/helpers/api-reference/token">
    Complete API documentation
  </Card>
</CardGroup>

## Need Help?

<CardGroup cols={2}>
  <Card title="Interactive Playground" icon="flask" href="https://playground.usedatabrain.com/">
    Experiment with live examples
  </Card>

  <Card title="Community & Support" icon="life-ring">
    Get help from our team
  </Card>
</CardGroup>
