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:
1

Check Browser Console

Open Developer Tools (F12) and look for errors in the Console tab
2

Verify Network Requests

Check the Network tab for failed API calls or 401/403 errors
3

Validate Token

Ensure your guest token is valid and not expired
4

Confirm IDs

Double-check dashboard-id and metric-id values
5

Test with Sample

Try the sample token/dashboard to isolate the issue

Common Issues

Dashboard Not Rendering

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:
// ✅ Correct - import first
import '@databrainhq/plugin/web';
import Dashboard from './Dashboard';

// ❌ Wrong - import after component
import Dashboard from './Dashboard';
import '@databrainhq/plugin/web';
  1. Check for web component support:
// Add this check
if (!customElements.get('dbn-dashboard')) {
  console.error('DataBrain web components not loaded');
}
  1. Verify container has height:
.dashboard-container {
  min-height: 600px; /* or 100vh */
}
  1. Check z-index conflicts:
dbn-dashboard {
  position: relative;
  z-index: 1;
}
Symptoms:
  • Dashboard appears briefly then vanishes
  • May happen on route changes or re-renders
Solutions:
  1. React: Prevent re-renders destroying the component:
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"
    />
  );
}
  1. Vue: Use v-show instead of v-if:
<!-- ✅ Better -->
<dbn-dashboard v-show="token" :token="token" />

<!-- ❌ May cause issues -->
<dbn-dashboard v-if="token" :token="token" />
  1. Check for parent component unmounting: Add key prop to prevent recreation
<Dashboard key="stable-key" />
Symptoms:
  • Loading spinner never stops
  • Dashboard never renders
Causes & Solutions:
  1. Invalid token:
// Check token format
console.log('Token:', token);
// Should be a UUID like: 3affda8b-7bd4-4a88-9687-105a94cfffab
  1. Wrong dashboard ID:
// Verify dashboard-id
console.log('Dashboard ID:', dashboardId);
// Should match ID from Data App
  1. Network blocked:
  • Check browser extensions (ad blockers, privacy tools)
  • Verify no corporate firewall blocking
  • Check CORS settings
  1. Token expired:
// Regenerate token on error
const handleTokenError = async () => {
  const newToken = await fetchFreshToken();
  setToken(newToken);
};

Authentication & Token Errors

Symptoms:
  • Error: “API key is invalid or expired”
  • 401 status in network tab
Solutions:
  1. Verify API token is correct:
# 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"}'
  1. Check token format:
// Should start with dbn_live_ or dbn_test_
const isValidFormat = apiToken.startsWith('dbn_');
if (!isValidFormat) {
  console.error('Invalid API token format');
}
  1. Ensure Bearer prefix:
// ✅ Correct
headers: {
  'Authorization': `Bearer ${apiToken}`
}

// ❌ Wrong
headers: {
  'Authorization': apiToken
}
  1. Regenerate API token:
  • Go to Data App settings
  • Generate new API token
  • Update environment variables
Symptoms:
  • “Token has expired” message
  • Dashboard stops working after some time
Solutions:
  1. Set appropriate expiry time:
// Backend token generation
{
  clientId: userId,
  dataAppName: 'your-app',
  expiryTime: 3600000 // 1 hour (adjust as needed)
}
  1. Implement token refresh:
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;
}
  1. Handle token expiry event:
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"
/>
Symptoms:
  • “Access to fetch blocked by CORS policy”
  • Cross-origin errors in console
Solutions:
  1. Generate tokens from backend (not frontend):
// ✅ 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')
  1. Whitelist your domain:
  • Go to Data App settings
  • Add your domains to allowed origins
  • Include all environments (dev, staging, prod)
  1. Check for mixed content (HTTP/HTTPS):
// Ensure HTTPS if embedding on HTTPS site
const apiUrl = window.location.protocol === 'https:' 
  ? 'https://api.usedatabrain.com'
  : 'http://api.usedatabrain.com';

Display & Styling Issues

Symptoms:
  • Dashboard hidden behind other elements
  • Modals or dropdowns don’t appear correctly
Solutions:
  1. Set appropriate z-index:
dbn-dashboard {
  position: relative;
  z-index: 10;
}

/* If dashboard needs to be on top */
dbn-dashboard::part(modal) {
  z-index: 9999;
}
  1. Check parent container:
.dashboard-container {
  position: relative;
  z-index: auto; /* Don't create new stacking context */
}
  1. Use isolation:
.dashboard-wrapper {
  isolation: isolate;
}
Symptoms:
  • Dashboard doesn’t fit screen
  • Charts overlap on mobile
  • Scrolling issues
Solutions:
  1. Ensure container is responsive:
.dashboard-container {
  width: 100%;
  max-width: 100vw;
  min-height: 600px;
  overflow: auto;
}

@media (max-width: 768px) {
  .dashboard-container {
    min-height: 400px;
  }
}
  1. Set viewport meta tag:
<meta name="viewport" content="width=device-width, initial-scale=1">
  1. Use responsive theme:
const theme = {
  general: {
    primaryColor: '#0066CC'
  },
  responsive: {
    breakpoints: {
      mobile: 768,
      tablet: 1024
    }
  }
};
Symptoms:
  • Custom colors not showing
  • Font changes not working
  • Theme options ignored
Solutions:
  1. Stringify theme object:
// ✅ Correct
<dbn-dashboard 
  theme={JSON.stringify(themeObject)}
/>

// ❌ Wrong
<dbn-dashboard 
  theme={themeObject}
/>
  1. Check theme structure:
const theme = {
  general: {
    primaryColor: '#0066CC',
    backgroundColor: '#FFFFFF',
    fontFamily: 'Inter, sans-serif'
  },
  chart: {
    colors: ['#0066CC', '#00C2B8'] // Array of colors
  }
};
  1. Verify CSS specificity:
/* Your styles might be overriding */
dbn-dashboard {
  all: initial; /* Reset if needed */
}

Performance Issues

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
  • Enable query result caching
  • Set appropriate TTL
  1. Apply filters to limit data:
const tokenRequest = {
  clientId: userId,
  dataAppName: 'your-app',
  params: {
    dashboardAppFilters: [{
      dashboardId: 'dashboard-id',
      values: {
        date_range: {
          startDate: '2024-01-01',
          endDate: '2024-03-31'
        }
      }
    }]
  }
};
  1. Optimize metrics:
  • Reduce number of data points
  • Use aggregations
  • Limit table rows
  • Consider pagination
  1. Lazy load dashboards:
import { lazy, Suspense } from 'react';

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

<Suspense fallback={<Loader />}>
  <Dashboard />
</Suspense>
Symptoms:
  • Page slows down over time
  • Browser tab crashes
  • Increasing memory usage
Solutions:
  1. Clean up on unmount:
useEffect(() => {
  const dashboard = document.querySelector('dbn-dashboard');
  
  return () => {
    // Clean up event listeners
    if (dashboard) {
      dashboard.removeEventListener('*', handleEvent);
    }
  };
}, []);
  1. Remove event listeners:
// Don't recreate handler on every render
const handleEvent = useCallback((event) => {
  // Handle event
}, []);
  1. Limit re-renders:
// Use memo for expensive components
const MemoizedDashboard = React.memo(Dashboard);

Framework-Specific Issues

Issue: Component not updating on prop changes
// ✅ Solution: Use useEffect
useEffect(() => {
  const element = document.querySelector('dbn-dashboard');
  if (element && token) {
    element.setAttribute('token', token);
  }
}, [token]);
Issue: TypeScript errors
// Add type declaration
declare global {
  namespace JSX {
    interface IntrinsicElements {
      'dbn-dashboard': any;
      'dbn-metric': any;
    }
  }
}
Issue: Next.js SSR errors
// Use dynamic import with ssr: false
import dynamic from 'next/dynamic';

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

Debugging Tips

Enable Debug Mode

Add debug logging to your implementation:
// Frontend debugging
window.DATABRAIN_DEBUG = true;

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

Inspect Component State

// 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

// 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);
};

Test Token Validity

async function validateToken(token) {
  try {
    const response = await fetch(
      'https://api.usedatabrain.com/api/v2/validate-token',
      {
        headers: { 'Authorization': `Bearer ${token}` }
      }
    );
    
    const data = await response.json();
    console.log('Token valid:', data.valid);
    console.log('Expires:', data.expiresAt);
    
    return data.valid;
  } catch (error) {
    console.error('Token validation failed:', error);
    return false;
  }
}

Error Messages Reference

Error MessageCauseSolution
Token is invalid or expiredExpired or malformed guest tokenRegenerate token from backend
Dashboard not foundWrong dashboard IDVerify dashboard-id attribute
Unauthorized accessNo permission to view dashboardCheck Data App permissions
CORS policy errorFrontend trying to call API directlyGenerate tokens from backend
Failed to fetchNetwork or firewall issueCheck network connectivity
Invalid data appWrong dataAppName in token requestVerify Data App name
Rate limit exceededToo many API callsImplement rate limiting/caching

Getting Help

If you’re still stuck after trying these solutions:

Best Practices to Avoid Issues

Never expose API tokens in frontend code. Use your backend to generate guest tokens.
Always handle token generation failures and network errors gracefully.
Type safety helps catch issues during development.
Verify your implementation works in Chrome, Firefox, Safari, and Edge.
Set up error tracking (Sentry, LogRocket) to catch issues early.