SDK-based embedding

Toucan AI supports SDK-based embedding for developers who want more control and flexibility when integrating analytics into their applications. This method is ideal for React, Next.js, Vue, and vanilla JavaScript projects that need to programmatically mount, update, or unmount embedded dashboards and charts.

How It Works

  • Loader Script: The SDK-based approach still relies on the Toucan AI web component loader:

    <script type="module" src="https://toucanai.cloud/embed/embed.js"></script>
  • Programmatic Mounting: Instead of static HTML, you create and configure the <tc-dashboard> or <tc-chart> element in your application code (JavaScript/TypeScript), then mount it to a container.

  • Token Management: Secure embed tokens are fetched from your backend (never hardcoded), then set as an attribute on the component.

  • Framework Support:

    • React/Next.js: Use useEffect to fetch tokens and mount/unmount the component.

    • Vue: Use onMounted/onUnmounted lifecycle hooks.

    • Vanilla JS: Use standard DOM APIs and event listeners.

Example (React)

import { useEffect, useState } from 'react';

function ToucanDashboard() {
  const [token, setToken] = useState('');

  useEffect(() => {
    async function getToken() {
      const response = await fetch('/api/toucan/token');
      const data = await response.json();
      setToken(data.token);
    }
    getToken();
  }, []);

  useEffect(() => {
    if (!token) return;
    const dashboard = document.createElement('tc-dashboard');
    dashboard.setAttribute('token', token);
    dashboard.setAttribute('dashboard-id', 'your-dashboard-id');
    dashboard.setAttribute('data-theme', 'light');
    const container = document.getElementById('toucan-container');
    container?.appendChild(dashboard);
    return () => { container?.removeChild(dashboard); };
  }, [token]);

  return <div id="toucan-container" style={{ height: '600px' }} />;
}

Key Features

  • Dynamic Control: Mount, update, or remove embedded analytics at runtime.

  • Framework Integration: Works seamlessly with React, Next.js, Vue, and plain JS.

  • Secure: Always uses server-generated, short-lived tokens.

  • Customizable: All web component attributes and theming options are available.

When to Use

  • You need to embed analytics in a dynamic, single-page app.

  • You want to control embedding lifecycle in code (e.g., show/hide, update on route change).

  • You’re building with React, Next.js, Vue, or similar frameworks.

Limitations

  • Still relies on the web component under the hood.

  • For deep API integration or custom data flows, consider the API-based method.

Last updated