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

export const details_0 = "The React SDK is built on embedding."

<Info>
  Available on the [Enterprise plan](/docs/administration/pricing). {details_0}
</Info>

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
* Models
* 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 />
```

Pass `dashboardId` to open a specific dashboard. Add `hideSidebar` when your application provides its own navigation:

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

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

### Models

`BasedashModels` shows models and hides the other primary features.

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

Models 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
  hideModels
  hideSuggestedPrompts
/>
```

The supported configuration props are:

* `theme`: `light`, `dark`, or `auto`
* `hideOrgName`
* `hideChat`
* `hideDashboards`
* `hideInsights`
* `hideAutomations`
* `hideModels`
* `hideSuggestedPrompts`
* `hideSidebar`
* `initialPage`: the page to open, such as `{ type: "dashboard", id: dashboardId }`

At least one of chat, dashboards, insights, automations, or models must remain visible. If all five 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.

## Open a specific page

Each feature component accepts an ID prop that opens that item instead of the feature's home page. ID props require `@basedash/embed` 0.3.0 or later.

| Component | Prop | `initialPage.type` on `BasedashApp` |
| - | - | - |
| `BasedashChat` | `chatId` | `chat` |
| `BasedashDashboards` | `dashboardId` | `dashboard` |
| `BasedashInsights` | `insightId` | `insight` |
| `BasedashAutomations` | `automationId` | `automation` |
| `BasedashModels` | `modelId` | `model` |

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

For `BasedashApp`, pass `initialPage` instead:

```tsx theme={"dark"}
<BasedashApp initialPage={{ type: "automation", id: "clx2a1b3c0001" }} />
```

The ID only chooses where the embed opens. Users can still navigate elsewhere unless you also hide the sidebar and other features. Basedash opens the default page instead when the item's feature is hidden or disabled for the organization, and shows a not-found page for an ID that doesn't exist or that the user can't access.

Changing the ID reloads the iframe on the new page. Under a `fetchToken` provider, the component fetches a fresh token first, because the original may have expired, and keeps showing the current page until it arrives. If you pass `token` yourself, make sure it is still valid when the ID changes.

## Hide the sidebar

`hideSidebar` removes the embed sidebar entirely, including the button, keyboard shortcut, and command menu entry that would reopen it. Every authenticated component accepts it in `@basedash/embed` 0.3.0 or later. It defaults to `false`.

Pair it with a single feature component and an ID prop when your application owns navigation, for example a page per dashboard:

```tsx theme={"dark"}
<BasedashProvider fetchToken={fetchToken}>
  <BasedashDashboards dashboardId={dashboardId} hideSidebar />
</BasedashProvider>
```

Hiding the sidebar is presentation only. Use Basedash permissions to control what each user can access. See [hiding the sidebar](/docs/developers/embedding#hide-the-sidebar) for details.

## 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/developers/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/developers/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/developers/embedding)
* [API reference](/docs/api-reference/overview)
* [Filters and variables](/docs/features/filters-and-variables)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.