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

# React SDK

> Embed Basedash with typed React components and server-side JWT helpers

The `@basedash/embed` SDK is the recommended way to embed Basedash in a React application. It wraps the existing iframe integration with typed components and provides server-only helpers for creating authentication tokens.

Use the SDK to embed:

* AI chat
* The interactive dashboards workspace
* Insights
* Automations
* The full Basedash app with selected features
* A read-only shared dashboard

The SDK is open source at [github.com/Basedash/embed](https://github.com/Basedash/embed).

## Install the SDK

```bash theme={"dark"}
npm install @basedash/embed
```

The SDK supports React 18.2 and React 19.

## Before you start

1. Go to **Settings → Embedding** and enable full app embedding.
2. Add your application's production origins to the allowed origins list.
3. Copy your JWT secret from **Settings → Security**.
4. Store the secret in your server environment. Never expose it to browser code or a public environment variable.

You also need your Basedash organization ID. If you provision customer organizations through the [Basedash API](/docs/api-reference/overview), create them with `fullEmbedEnabled: true` and store the returned organization ID and JWT secret on your server.

## Create a token endpoint

Your backend must authenticate the current user, confirm that they can access the customer organization, and create a short-lived Basedash token.

<CodeGroup>
  ```ts Next.js theme={"dark"}
  import { createEmbedToken } from "@basedash/embed/server";

  export async function GET() {
    // Replace this with the user from your authenticated server session.
    const user = {
      email: "jane@example.com",
      firstName: "Jane",
      lastName: "Doe",
    };

    const secret = process.env.BASEDASH_EMBED_JWT_SECRET;
    const orgId = process.env.BASEDASH_ORG_ID;

    if (!secret || !orgId) {
      return new Response("Basedash is not configured", { status: 500 });
    }

    const token = await createEmbedToken({
      secret,
      orgId,
      user: {
        ...user,
        role: "MEMBER",
      },
    });

    return new Response(token, {
      headers: {
        "Cache-Control": "no-store",
        "Content-Type": "text/plain",
      },
    });
  }
  ```

  ```ts Express theme={"dark"}
  import { createEmbedToken } from "@basedash/embed/server";

  app.get("/api/basedash-token", requireUser, async (req, res) => {
    const secret = process.env.BASEDASH_EMBED_JWT_SECRET;
    const orgId = process.env.BASEDASH_ORG_ID;

    if (!secret || !orgId) {
      return res.status(500).send("Basedash is not configured");
    }

    const token = await createEmbedToken({
      secret,
      orgId,
      user: {
        email: req.user.email,
        firstName: req.user.firstName,
        lastName: req.user.lastName,
        role: "MEMBER",
      },
    });

    res.set("Cache-Control", "no-store").type("text/plain").send(token);
  });
  ```
</CodeGroup>

`createEmbedToken` signs an HS256 JWT and defaults to a 10-minute expiration. The token identifies the user and organization. Basedash creates the user and organization membership on their first authenticated embed load.

<Warning>
  Only import `createEmbedToken` from `@basedash/embed/server` in trusted server
  code. Anyone with your JWT secret can impersonate users in that Basedash
  organization.
</Warning>

## Add the provider

In your React application, fetch the token from your backend and pass the callback to `BasedashProvider`.

```tsx theme={"dark"}
"use client";

import { BasedashChat, BasedashProvider } from "@basedash/embed/react";
import { useCallback } from "react";

export function AnalyticsPage() {
  const fetchToken = useCallback(async () => {
    const response = await fetch("/api/basedash-token");

    if (!response.ok) {
      throw new Error("Could not create a Basedash token");
    }

    return response.text();
  }, []);

  return (
    <BasedashProvider fetchToken={fetchToken} theme="auto">
      <BasedashChat
        loadingFallback={<p>Loading analytics…</p>}
        style={{ height: 720 }}
      />
    </BasedashProvider>
  );
}
```

The provider fetches one token per mount. Components beneath the same provider reuse it.

If your React tree already receives a server-generated token, pass it directly:

```tsx theme={"dark"}
<BasedashProvider token={token}>
  <BasedashChat />
</BasedashProvider>
```

You can also pass `token` directly to an individual component without a provider.

## Choose a component

### Chat

`BasedashChat` shows AI chat and hides the other primary Basedash features. It hides the organization name by default.

```tsx theme={"dark"}
<BasedashChat hideSuggestedPrompts />
```

### Dashboards

`BasedashDashboards` shows the interactive dashboards workspace, including dashboard and chart creation, and hides the other primary features.

```tsx theme={"dark"}
<BasedashDashboards />
```

### Insights

`BasedashInsights` shows insights and hides the other primary features.

```tsx theme={"dark"}
<BasedashInsights />
```

Insights must be enabled for the organization.

### Automations

`BasedashAutomations` shows automations and hides the other primary features.

```tsx theme={"dark"}
<BasedashAutomations />
```

Automations must be enabled for the organization.

### Full app

`BasedashApp` shows the complete embed by default. Use props to select which features remain available.

```tsx theme={"dark"}
<BasedashApp hideOrgName hideInsights hideAutomations hideSuggestedPrompts />
```

The supported configuration props are:

* `theme`: `light`, `dark`, or `auto`
* `hideOrgName`
* `hideChat`
* `hideDashboards`
* `hideInsights`
* `hideAutomations`
* `hideSuggestedPrompts`

At least one of chat, dashboards, insights, or automations must remain visible. If all four are hidden, Basedash falls back to chat.

### Shared dashboard

`BasedashSharedDashboard` renders a read-only dashboard from a public sharing link. It does not require a provider or user token.

```tsx theme={"dark"}
<BasedashSharedDashboard publicSharingLinkId="abc123" />
```

Enable sharing from the dashboard's **Share** menu and use the ID from the resulting `/shared/{id}` URL.

## Lock shared dashboard filters

For customer-specific or user-specific shared dashboards, create a secure filter token on your server.

```ts theme={"dark"}
import { createDashboardFilterToken } from "@basedash/embed/server";

const filterToken = await createDashboardFilterToken({
  secret: process.env.BASEDASH_EMBED_JWT_SECRET,
  dashboardLinkId: "abc123",
  params: {
    company_id: "company_456",
    regions: ["us", "ca"],
  },
});
```

Pass the result to the shared dashboard:

```tsx theme={"dark"}
<BasedashSharedDashboard
  publicSharingLinkId="abc123"
  filterToken={filterToken}
/>
```

Locked filters are applied server-side, hidden from viewers, and cannot be changed in the browser. See [secure filtering](/docs/features/embedding#secure-filtering) for filter behavior and security considerations.

## Customize the frame

All components accept:

* `className` and `style` for the outer container
* `iframeProps` for the underlying iframe
* `loadingFallback`, shown until the iframe loads
* `errorFallback`, shown if token fetching fails
* `title` for the iframe's accessible name
* `instanceUrl` for self-hosted Basedash

```tsx theme={"dark"}
<BasedashDashboards
  className="analytics"
  style={{ minHeight: 640 }}
  iframeProps={{
    allow: "clipboard-write; fullscreen",
    onLoad: () => console.log("Basedash loaded"),
  }}
/>
```

The iframe defaults to full width and height, no border, `allow="clipboard-write"`, and eager loading.

## Handle token errors

Use `errorFallback` to keep an authentication failure inside your page layout:

```tsx theme={"dark"}
<BasedashChat
  errorFallback={(error) => (
    <p>Analytics could not be loaded: {error.message}</p>
  )}
/>
```

The `useBasedash()` hook exposes the current `token`, `status`, `error`, and a `refreshToken()` method for custom controls.

## Self-hosted Basedash

Set `instanceUrl` on the provider:

```tsx theme={"dark"}
<BasedashProvider
  fetchToken={fetchToken}
  instanceUrl="https://analytics.example.com"
>
  <BasedashApp />
</BasedashProvider>
```

Server-side token generation is the same for cloud and self-hosted instances.

## Non-React applications

For Vue, Svelte, server-rendered HTML, or other applications, use the [raw iframe integration](/docs/features/embedding). The framework-independent `buildEmbedUrl` helper is also available from `@basedash/embed` if your project uses JavaScript or TypeScript without React.

## Current limitations

* SDK components render Basedash through iframes; they do not render Basedash UI natively.
* Auto-resizing, navigation callbacks, and host-triggered actions are not available because Basedash does not currently expose an iframe messaging API.
* Shared dashboards are supported, but Basedash does not currently expose standalone shared-chart embeds.

## Related pages

* [Raw iframe embedding](/docs/features/embedding)
* [API reference](/docs/api-reference/overview)
* [Filters and variables](/docs/features/filters-and-variables)
