> ## 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.

# Troubleshooting Guide

> Common issues and solutions for embedded DataBrain dashboards

This guide covers common issues you might encounter when embedding DataBrain and how to resolve them.

## Quick Diagnostics Checklist

Before diving into specific issues, run through this checklist:

<Steps>
  <Step title="Check Browser Console">
    Open Developer Tools (F12) and look for errors in the Console tab
  </Step>

  <Step title="Verify Network Requests">
    Check the Network tab for failed API calls or 401/403 errors
  </Step>

  <Step title="Validate Token">
    Ensure your guest token is valid and not expired
  </Step>

  <Step title="Confirm IDs">
    Double-check dashboard-id and metric-id values
  </Step>

  <Step title="Test with Sample">
    Try the sample token/dashboard to isolate the issue
  </Step>
</Steps>

## Common Issues

### Dashboard Not Rendering

<AccordionGroup>
  <Accordion title="Component shows blank or nothing renders" icon="eye-slash">
    **Symptoms:**

    * Empty space where dashboard should be
    * No errors in console
    * Component seems to load but shows nothing

    **Solutions:**

    1. **Ensure plugin is imported before rendering:**

    ```javascript theme={"dark"}
    // ✅ Correct - import first
    import '@databrainhq/plugin/web';
    import Dashboard from './Dashboard';

    // ❌ Wrong - import after component
    import Dashboard from './Dashboard';
    import '@databrainhq/plugin/web';
    ```

    2. **Check for web component support:**

    ```javascript theme={"dark"}
    // Add this check
    if (!customElements.get('dbn-dashboard')) {
      console.error('DataBrain web components not loaded');
    }
    ```

    3. **Verify container has height:**

    ```css theme={"dark"}
    .dashboard-container {
      min-height: 600px; /* or 100vh */
    }
    ```

    4. **Check z-index conflicts:**

    ```css theme={"dark"}
    dbn-dashboard {
      position: relative;
      z-index: 1;
    }
    ```
  </Accordion>

  <Accordion title="Dashboard loads then disappears" icon="ghost">
    **Symptoms:**

    * Dashboard appears briefly then vanishes
    * May happen on route changes or re-renders

    **Solutions:**

    1. **React: Prevent re-renders destroying the component:**

    ```javascript theme={"dark"}
    import { useRef, useEffect } from 'react';

    function Dashboard({ token }) {
      const dashboardRef = useRef(null);

      useEffect(() => {
        if (dashboardRef.current && token) {
          dashboardRef.current.setAttribute('token', token);
        }
      }, [token]);

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

    2. **Vue: Use v-show instead of v-if:**

    ```vue theme={"dark"}
    <!-- ✅ Better -->
    <dbn-dashboard v-show="token" :token="token" />

    <!-- ❌ May cause issues -->
    <dbn-dashboard v-if="token" :token="token" />
    ```

    3. **Check for parent component unmounting:**
       Add key prop to prevent recreation

    ```javascript theme={"dark"}
    <Dashboard key="stable-key" />
    ```
  </Accordion>

  <Accordion title="Spinner loads infinitely" icon="spinner">
    **Symptoms:**

    * Loading spinner never stops
    * Dashboard never renders

    **Causes & Solutions:**

    1. **Invalid token:**

    ```javascript theme={"dark"}
    // Check token format
    console.log('Token:', token);
    // Should be a UUID like: 3affda8b-7bd4-4a88-9687-105a94cfffab
    ```

    2. **Wrong dashboard ID:**

    ```javascript theme={"dark"}
    // Verify dashboard-id
    console.log('Dashboard ID:', dashboardId);
    // Should match ID from Data App
    ```

    3. **Network blocked:**

    * Check browser extensions (ad blockers, privacy tools)
    * Verify no corporate firewall blocking
    * Check CORS settings
  </Accordion>
</AccordionGroup>

### Authentication & Token Errors

<AccordionGroup>
  <Accordion title="401 Unauthorized Error" icon="lock">
    **Symptoms:**

    * Error: "API key is invalid or expired"
    * 401 status in network tab

    **Solutions:**

    1. **Verify API token is correct:**

    ```bash theme={"dark"}
    # Test API token
    curl --request POST \
      --url https://api.usedatabrain.com/api/v2/guest-token/create \
      --header 'Authorization: Bearer YOUR_API_TOKEN' \
      --header 'Content-Type: application/json' \
      --data '{"clientId":"test","dataAppName":"your-app"}'
    ```

    2. **Ensure Bearer prefix:**

    ```javascript theme={"dark"}
    // ✅ Correct
    headers: {
      'Authorization': `Bearer ${apiToken}`
    }

    // ❌ Wrong
    headers: {
      'Authorization': apiToken
    }
    ```

    3. **Regenerate API token:**

    * Go to Data App settings
    * Generate new API token
    * Update environment variables
  </Accordion>

  <Accordion title="Token Expired Error" icon="clock">
    **Symptoms:**

    * "Token has expired" message
    * Dashboard stops working after some time

    **Solutions:**

    1. **Set appropriate expiry time:**

    ```javascript theme={"dark"}
    // Backend token generation
    {
      clientId: userId,
      dataAppName: 'your-app',
      expiryTime: 3600000 // 1 hour (adjust as needed)
    }
    ```

    2. **Implement token refresh:**

    ```javascript theme={"dark"}
    import { useEffect, useState, useCallback } from 'react';

    function useDataBrainToken() {
      const [token, setToken] = useState(null);

      const refreshToken = useCallback(async () => {
        const response = await fetch('/api/databrain/guest-token');
        const data = await response.json();
        setToken(data.token);
      }, []);

      useEffect(() => {
        refreshToken();
        
        // Refresh token every 50 minutes (if set to 1 hour expiry)
        const interval = setInterval(refreshToken, 50 * 60 * 1000);
        
        return () => clearInterval(interval);
      }, [refreshToken]);

      return token;
    }
    ```

    3. **Handle token expiry event:**

    ```javascript theme={"dark"}
    window.handleTokenExpiry = async (event) => {
      if (event.type === 'TOKEN_EXPIRED') {
        const newToken = await fetchFreshToken();
        // Update token in component
        document.querySelector('dbn-dashboard')
          .setAttribute('token', newToken);
      }
    };

    <dbn-dashboard 
      handle-server-event="handleTokenExpiry"
    />
    ```
  </Accordion>

  <Accordion title="CORS Errors" icon="shield-halved">
    **Symptoms:**

    * "Access to fetch blocked by CORS policy"
    * Cross-origin errors in console

    **Solutions:**

    1. **Generate tokens from backend (not frontend):**

    ```javascript theme={"dark"}
    // ✅ Correct - backend generates token
    // backend/api/token.js
    const token = await generateGuestToken(userId);

    // ❌ Wrong - frontend trying to generate
    // Causes CORS errors
    fetch('https://api.usedatabrain.com/api/v2/guest-token/create')
    ```

    2. **Whitelist your domain:**

    * Go to Data App settings
    * Add your domains to allowed origins
    * Include all environments (dev, staging, prod)

    3. **Check for mixed content (HTTP/HTTPS):**

    ```javascript theme={"dark"}
    // Ensure HTTPS if embedding on HTTPS site
    const apiUrl = window.location.protocol === 'https:' 
      ? 'https://api.usedatabrain.com'
      : 'http://api.usedatabrain.com';
    ```
  </Accordion>
</AccordionGroup>

### Display & Styling Issues

<AccordionGroup>
  <Accordion title="Dashboard overlaps or z-index issues" icon="layer-group">
    **Symptoms:**

    * Dashboard hidden behind other elements
    * Modals or dropdowns don't appear correctly

    **Solutions:**

    1. **Set appropriate z-index:**

    ```css theme={"dark"}
    dbn-dashboard {
      position: relative;
      z-index: 10;
    }

    /* If dashboard needs to be on top */
    dbn-dashboard::part(modal) {
      z-index: 9999;
    }
    ```

    2. **Check parent container:**

    ```css theme={"dark"}
    .dashboard-container {
      position: relative;
      z-index: auto; /* Don't create new stacking context */
    }
    ```

    3. **Use isolation:**

    ```css theme={"dark"}
    .dashboard-wrapper {
      isolation: isolate;
    }
    ```
  </Accordion>

  <Accordion title="Responsive layout issues" icon="mobile">
    **Symptoms:**

    * Dashboard doesn't fit screen
    * Charts overlap on mobile
    * Scrolling issues

    **Solutions:**

    1. **Ensure container is responsive:**

    ```css theme={"dark"}
    .dashboard-container {
      width: 100%;
      max-width: 100vw;
      min-height: 600px;
      overflow: auto;
    }

    @media (max-width: 768px) {
      .dashboard-container {
        min-height: 400px;
      }
    }
    ```

    2. **Set viewport meta tag:**

    ```html theme={"dark"}
    <meta name="viewport" content="width=device-width, initial-scale=1">
    ```

    3. **Use responsive theme:**

    ```javascript theme={"dark"}
    const theme = {
      general: {
        primaryColor: '#0066CC'
      },
      responsive: {
        breakpoints: {
          mobile: 768,
          tablet: 1024
        }
      }
    };
    ```
  </Accordion>

  <Accordion title="Theme not applying" icon="palette">
    **Symptoms:**

    * Custom colors not showing
    * Font changes not working
    * Theme options ignored

    **Solutions:**

    1. **Stringify theme object:**

    ```javascript theme={"dark"}
    // ✅ Correct
    <dbn-dashboard 
      theme={JSON.stringify(themeObject)}
    />

    // ❌ Wrong
    <dbn-dashboard 
      theme={themeObject}
    />
    ```

    2. **Check theme structure:**

    ```javascript theme={"dark"}
    const theme = {
      general: {
        primaryColor: '#0066CC',
        backgroundColor: '#FFFFFF',
        fontFamily: 'Inter, sans-serif'
      },
      chart: {
        colors: ['#0066CC', '#00C2B8'] // Array of colors
      }
    };
    ```

    3. **Verify CSS specificity:**

    ```css theme={"dark"}
    /* Your styles might be overriding */
    dbn-dashboard {
      all: initial; /* Reset if needed */
    }
    ```
  </Accordion>
</AccordionGroup>

### Performance Issues

<AccordionGroup>
  <Accordion title="Slow loading dashboard" icon="gauge">
    **Symptoms:**

    * Dashboard takes long to load
    * Metrics render slowly
    * Poor performance with large datasets

    **Solutions:**

    1. **Enable caching in workspace settings:**

    * Go to **Workspace Settings → Cache Settings**
    * Enable query result caching
    * Set an appropriate TTL (start with 3600 seconds / 1 hour)
    * Choose **DataBrain Caching** for quick setup, or **BYOC** if you have your own Redis
    * See the [Cache Settings guide](/guides/onboarding-and-configuration/workspace-settings/cache-settings) for detailed setup

    2. **Apply filters to limit data:**

    ```javascript theme={"dark"}
    const tokenRequest = {
      clientId: userId,
      dataAppName: 'your-app',
      params: {
        dashboardAppFilters: [{
          dashboardId: 'dashboard-id',
          values: {
            date_range: {
              startDate: '2024-01-01',
              endDate: '2024-03-31'
            }
          }
        }]
      }
    };
    ```

    3. **Optimize metrics:**

    * Reduce number of data points
    * Use aggregations
    * Limit table rows
    * Consider pagination

    4. **Lazy load dashboards:**

    ```javascript theme={"dark"}
    import { lazy, Suspense } from 'react';

    const Dashboard = lazy(() => import('./Dashboard'));

    <Suspense fallback={<Loader />}>
      <Dashboard />
    </Suspense>
    ```
  </Accordion>

  <Accordion title="Memory leaks" icon="memory">
    **Symptoms:**

    * Page slows down over time
    * Browser tab crashes
    * Increasing memory usage

    **Solutions:**

    1. **Clean up on unmount:**

    ```javascript theme={"dark"}
    useEffect(() => {
      const dashboard = document.querySelector('dbn-dashboard');
      
      return () => {
        // Clean up event listeners
        if (dashboard) {
          dashboard.removeEventListener('*', handleEvent);
        }
      };
    }, []);
    ```

    2. **Remove event listeners:**

    ```javascript theme={"dark"}
    // Don't recreate handler on every render
    const handleEvent = useCallback((event) => {
      // Handle event
    }, []);
    ```

    3. **Limit re-renders:**

    ```javascript theme={"dark"}
    // Use memo for expensive components
    const MemoizedDashboard = React.memo(Dashboard);
    ```
  </Accordion>
</AccordionGroup>

### Cache & Redis Issues

<AccordionGroup>
  <Accordion title="Stale data displayed after data updates" icon="clock-rotate-left">
    **Symptoms:**

    * Dashboard shows old data after an ETL run or manual data update
    * Different users see inconsistent data

    **Solutions:**

    1. **Reset cache after data updates:**

    * Go to **Workspace Settings → Cache Settings** and click **Reset Cache**
    * This flushes all cached query results for the workspace

    2. **Reduce cache TTL:**

    * If your data updates frequently, lower the cache expiration time
    * For hourly updates, set TTL to `3600` (1 hour) or less

    3. **Verify cache is the cause:**

    * Temporarily disable caching in **Workspace Settings → Cache Settings**
    * If the data is now correct, caching was serving stale results
  </Accordion>

  <Accordion title="BYOC Redis connection failures" icon="plug-circle-xmark">
    **Symptoms:**

    * Cache settings fail to save with "Invalid Redis credentials" error
    * Caching enabled but no speed improvement on repeat dashboard loads

    **Solutions:**

    1. **Check network connectivity:**

    * Your Redis must be reachable from DataBrain's cloud
    * Verify your security group allows inbound on the Redis port (default `6379`) from DataBrain's IP (see [Allow Access to our IP](/guides/datasources/allow-access-to-our-ip))
    * If your Redis is in a private network, contact DataBrain support for connectivity options

    2. **Verify credentials:**

    * Double-check the host, port, and AUTH token
    * Ensure the AUTH token matches what's configured on your Redis instance
    * Try connecting to your Redis from another client to rule out credential issues

    3. **Check Redis is running:**

    * Ensure your Redis/Elasticache instance is in an "Available" state
    * Check for maintenance windows or failover events

    4. **Connection timeout:**

    * DataBrain uses a 5-second connection timeout
    * If your Redis has high network latency (e.g., cross-region), connections may time out
  </Accordion>

  <Accordion title="Cache not improving performance" icon="gauge">
    **Symptoms:**

    * Caching is enabled but dashboards aren't loading faster
    * Every request seems to hit the database

    **Solutions:**

    1. **Verify caching is enabled:**

    * Go to **Workspace Settings → Cache Settings** and confirm the toggle is on
    * Confirm you've set a TTL greater than 0

    2. **Check cache mode:**

    * If using **Databrain Caching**, it should work automatically
    * If using **BYOC**, verify your Redis connection was validated successfully (save must succeed)

    3. **Understand cache key behavior:**

    * Cache keys include the full query, filters, workspace ID, and datasource ID
    * Changing any filter or parameter generates a new cache key
    * Dashboards with many dynamic filters may have lower cache hit rates

    4. **Check TTL is reasonable:**

    * Very short TTLs (e.g., 10 seconds) mean cache entries expire before they can be reused
    * Start with `3600` (1 hour) and adjust based on your needs
  </Accordion>
</AccordionGroup>

### Framework-Specific Issues

<Tabs>
  <Tab title="React">
    **Issue: Component not updating on prop changes**

    ```javascript theme={"dark"}
    // ✅ Solution: Use useEffect
    useEffect(() => {
      const element = document.querySelector('dbn-dashboard');
      if (element && token) {
        element.setAttribute('token', token);
      }
    }, [token]);
    ```

    **Issue: TypeScript errors**

    ```typescript theme={"dark"}
    // Add type declaration
    declare global {
      namespace JSX {
        interface IntrinsicElements {
          'dbn-dashboard': any;
          'dbn-metric': any;
        }
      }
    }
    ```

    **Issue: Next.js SSR errors**

    ```javascript theme={"dark"}
    // Use dynamic import with ssr: false
    import dynamic from 'next/dynamic';

    const Dashboard = dynamic(
      () => import('../components/Dashboard'),
      { ssr: false }
    );
    ```
  </Tab>

  <Tab title="Vue">
    **Issue: Vue warnings about unknown custom element**

    ```javascript theme={"dark"}
    // vue.config.js or vite.config.js
    export default {
      compilerOptions: {
        isCustomElement: tag => tag.startsWith('dbn-')
      }
    }
    ```

    **Issue: Reactive props not updating**

    ```vue theme={"dark"}
    <!-- Use :key to force re-render -->
    <dbn-dashboard 
      :key="token"
      :token="token"
      dashboard-id="id"
    />
    ```
  </Tab>

  <Tab title="Angular">
    **Issue: CUSTOM\_ELEMENTS\_SCHEMA required**

    ```typescript theme={"dark"}
    // app.module.ts
    import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

    @NgModule({
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    export class AppModule { }
    ```

    **Issue: Change detection not working**

    ```typescript theme={"dark"}
    import { ChangeDetectorRef } from '@angular/core';

    constructor(private cdr: ChangeDetectorRef) {}

    updateToken(newToken: string) {
      this.token = newToken;
      this.cdr.detectChanges();
    }
    ```
  </Tab>
</Tabs>

## Debugging Tips

### Enable Debug Mode

Add debug logging to your implementation:

```javascript theme={"dark"}
// Frontend debugging
window.DATABRAIN_DEBUG = true;

// Will log:
// - Token generation
// - API requests
// - Component lifecycle
// - Event triggers
```

### Inspect Component State

```javascript theme={"dark"}
// Check component attributes
const dashboard = document.querySelector('dbn-dashboard');
console.log({
  token: dashboard.getAttribute('token'),
  dashboardId: dashboard.getAttribute('dashboard-id'),
  options: dashboard.getAttribute('options')
});
```

### Monitor Network Requests

```javascript theme={"dark"}
// Log all DataBrain API calls
const originalFetch = window.fetch;
window.fetch = function(...args) {
  if (args[0].includes('usedatabrain.com')) {
    console.log('DataBrain API call:', args);
  }
  return originalFetch.apply(this, args);
};
```

## Error Messages Reference

| Error Message                 | Cause                                | Solution                        |
| ----------------------------- | ------------------------------------ | ------------------------------- |
| `Token is invalid or expired` | Expired or malformed guest token     | Regenerate token from backend   |
| `Dashboard not found`         | Wrong dashboard ID                   | Verify dashboard-id attribute   |
| `Unauthorized access`         | No permission to view dashboard      | Check Data App permissions      |
| `CORS policy error`           | Frontend trying to call API directly | Generate tokens from backend    |
| `Failed to fetch`             | Network or firewall issue            | Check network connectivity      |
| `Invalid data app`            | Wrong dataAppName in token request   | Verify Data App name            |
| `Rate limit exceeded`         | Too many API calls                   | Implement rate limiting/caching |

## Getting Help

If you're still stuck after trying these solutions:

<CardGroup cols={2}>
  <Card title="Test Harness" icon="flask" href="/developer-docs/test-harness">
    Use our test environment to isolate issues
  </Card>

  <Card title="Sample Implementation" icon="code" href="https://playground.usedatabrain.com/">
    Check working examples in playground
  </Card>

  <Card title="API Documentation" icon="book" href="/developer-docs/helpers/api-reference/token">
    Review complete API specs
  </Card>

  <Card title="Support" icon="life-ring">
    Contact our support team
  </Card>
</CardGroup>

## Best Practices to Avoid Issues

<AccordionGroup>
  <Accordion title="Always generate tokens server-side" icon="server">
    Never expose API tokens in frontend code. Use your backend to generate guest tokens.
  </Accordion>

  <Accordion title="Implement error handling" icon="triangle-exclamation">
    Always handle token generation failures and network errors gracefully.
  </Accordion>

  <Accordion title="Use TypeScript" icon="code">
    Type safety helps catch issues during development.
  </Accordion>

  <Accordion title="Test across browsers" icon="browsers">
    Verify your implementation works in Chrome, Firefox, Safari, and Edge.
  </Accordion>

  <Accordion title="Monitor in production" icon="chart-line">
    Set up error tracking (Sentry, LogRocket) to catch issues early.
  </Accordion>
</AccordionGroup>
