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

# React

> Install and set up admesh-ui-sdk for automatic recommendation rendering and tracking

<Card title="Looking for Flutter?" icon="mobile" href="/ui-sdk/flutter">
  Use the AdMesh Flutter UI SDK for native recommendation rendering, tracking, and theming.
</Card>

## Quick Start

Get started with AdMesh in 3 simple steps:

<Steps>
  <Step title="Install the Package">
    ```bash theme={null}
    npm install admesh-ui-sdk@latest
    ```
  </Step>

  <Step title="Wrap Your App with AdMeshProvider">
    ```tsx theme={null}
    import { AdMeshProvider } from 'admesh-ui-sdk';

    <AdMeshProvider apiKey="your-api-key" sessionId={sessionId}>
      <YourApp />
    </AdMeshProvider>
    ```

    The provider initializes the SDK and manages your session context.
  </Step>

  <Step title="Choose Your Integration Format">
    Select the format that matches your use case:

    **Tail & Product Format** - Separate recommendations panel

    ```tsx theme={null}
    import { AdMeshRecommendations } from 'admesh-ui-sdk';

    {messages.map((msg) => (
      msg.role === 'assistant' && msg.userQuery && msg.userMessageId && (
        <AdMeshRecommendations
          key={msg.messageId}
          messageId={msg.userMessageId}  // Required: User message ID (not assistant message ID)
          query={msg.userQuery}  // Required: User's original query
        />
      )
    ))}
    ```

    **Weave Ad Format** - Embedded links in LLM responses

    ```tsx theme={null}
    import { WeaveAdFormatContainer } from 'admesh-ui-sdk';

    <WeaveAdFormatContainer
      messageId={message.messageId}
      query={userQuery}
      fallbackFormat="tail"
    >
      <YourLLMResponse />
    </WeaveAdFormatContainer>
    ```
  </Step>
</Steps>

***

## Core Concepts

### Session Management

AdMesh uses sessions to track user interactions across multiple messages:

* **Session ID**: Unique identifier for a user's conversation session
* **Message ID**: Unique identifier for each individual message/query

```tsx theme={null}
// Generate a session ID when user starts a conversation
const sessionId = crypto.randomBytes(16).toString('hex');

// Generate a message ID for each query
const messageId = crypto.randomBytes(7).toString('hex');
```

<Note>
  Your application is responsible for generating and managing session and message IDs. The SDK accepts these IDs but does not generate them.
</Note>

### Available Formats

AdMesh supports three recommendation formats:

| Format      | Use Case                        | Component                |
| ----------- | ------------------------------- | ------------------------ |
| **Tail**    | Inline tails with product links | `AdMeshRecommendations`  |
| **Product** | Product cards with details      | `AdMeshRecommendations`  |
| **Weave**   | Embedded links in LLM responses | `WeaveAdFormatContainer` |

<Card title="Flutter SDK Guide" icon="dart" href="/ui-sdk/flutter">
  See the native Flutter integration guide for `AdMeshSdk`, `AdMeshProvider`, `AdMeshRecommendations`, tracking, and theming.
</Card>

***

## Core Components

### AdMeshProvider

Context provider that initializes the SDK and manages session state. **Required** - wrap your entire app with this component.

```typescript theme={null}
interface AdMeshProviderProps {
  apiKey: string;            // Your AdMesh API key (required)
  sessionId: string;         // Current session ID (required)
  theme?: AdMeshTheme;       // Optional: Custom theme
  apiBaseUrl?: string;       // Optional: API base URL (defaults to production)
  language?: string;         // Optional: User language in BCP 47 format (e.g., "en-US")
  geo_country?: string;      // Optional: User country code in ISO 3166-1 alpha-2 format (e.g., "US")
  userId?: string;           // Optional: Anonymous hashed user ID
  model?: string;            // Optional: AI model identifier (e.g., "gpt-4o")
  messages?: Array<{ role: string; content: string; id?: string }>;  // Optional: Conversation history
  children: React.ReactNode; // Your app components
}
```

**Example:**

```tsx theme={null}
import { AdMeshProvider } from 'admesh-ui-sdk';

<AdMeshProvider apiKey="your-api-key" sessionId={sessionId}>
  <ChatInterface />
</AdMeshProvider>
```

***

### AdMeshRecommendations

Displays recommendations in a separate panel. Use for **Tail** or **Product** format.

```typescript theme={null}
interface AdMeshRecommendationsProps {
  messageId: string;                      // Required: Message ID (user message ID, not assistant message ID)
  query: string;                          // Required: User's original query
  onRecommendationsShown?: (messageId: string) => void;  // Optional: Callback when recommendations shown
  onError?: (error: Error) => void;       // Optional: Error handler
  onPasteToInput?: (content: string) => void;  // Optional: For bridge format CTA button
  followups_container_id?: string;        // Optional: Container ID for follow-up suggestions
  onExecuteQuery?: (query: string) => void | Promise<void>;  // Optional: Handler for follow-up queries
  onFollowupDetected?: (followupQuery: string, followupEngagementUrl: string, recommendationId: string) => void;  // Optional: Callback when follow-up detected
  isContainerReady?: boolean;             // Optional: Signal when follow-up container is ready
}
```

**Example:**

```tsx theme={null}
import { AdMeshRecommendations } from 'admesh-ui-sdk';

{messages.map((msg) => (
  msg.role === 'assistant' && msg.userQuery && msg.userMessageId && (
    <AdMeshRecommendations
      key={msg.messageId}
      messageId={msg.userMessageId}  // Required: User message ID (not assistant message ID)
      query={msg.userQuery}  // Required: User's original query
      followups_container_id={`admesh-followups-${msg.messageId}`}
      onExecuteQuery={(query) => sendMessage(query)}
    />
  )
))}
```

<Card title="Tail & Product Format Guide" icon="list" href="/platforms/tail-format">
  Complete integration guide for Tail & Product Format
</Card>

***

### WeaveAdFormatContainer

Wraps LLM response content and detects embedded AdMesh links. Use for **Weave Ad Format**.

```typescript theme={null}
interface WeaveAdFormatContainerProps {
  messageId: string;                      // Required: Assistant message ID
  query?: string;                         // Optional: User's query (for fallback recommendations)
  fallbackFormat?: 'tail' | 'product';   // Optional: Fallback format if no links found (default: 'tail')
  children: React.ReactNode;              // Required: LLM response content
  onLinksDetected?: (count: number) => void;  // Optional: Callback when links detected
  onNoLinksDetected?: () => void;        // Optional: Callback when no links detected
  onError?: (error: Error) => void;      // Optional: Error handler
  onFallbackChange?: (shouldFallback: boolean) => void;  // Optional: Callback when fallback state changes
  onWeaveAttempt?: (messageId: string) => void;  // Optional: Callback when weave injection attempted
  onWeaveOutcome?: (messageId: string, success: boolean, reason?: string) => void;  // Optional: Callback when weave outcome determined
  followups_container_id?: string;       // Optional: Container ID for follow-up suggestions
  onExecuteQuery?: (query: string) => void | Promise<void>;  // Optional: Handler for follow-up queries
  onFollowupDetected?: (followupQuery: string, followupEngagementUrl: string, recommendationId: string) => void;  // Optional: Callback when follow-up detected
  isContainerReady?: boolean;            // Optional: Signal when follow-up container is ready
  className?: string;                     // Optional: CSS class for container
}
```

**Example:**

```tsx theme={null}
import { WeaveAdFormatContainer } from 'admesh-ui-sdk';

<WeaveAdFormatContainer
  messageId={message.messageId}
  query={userQuery}
  fallbackFormat="tail"
>
  <Markdown>{message.content}</Markdown>
</WeaveAdFormatContainer>
```

<Card title="Weave Ad Format Guide" icon="link" href="/platforms/weave-ad-format">
  Complete integration guide for Weave Ad Format with event-driven architecture
</Card>

***

### Streaming Event Utilities

For **Weave Ad Format** only - dispatch events to coordinate link detection with streaming responses.

```typescript theme={null}
// Dispatch when streaming starts
dispatchStreamingStartEvent(messageId: string, sessionId: string): void

// Dispatch when streaming completes
dispatchStreamingCompleteEvent(messageId: string, sessionId: string, metadata?: object): void
```

**Example:**

```tsx theme={null}
import {
  dispatchStreamingStartEvent,
  dispatchStreamingCompleteEvent
} from 'admesh-ui-sdk';

// When assistant message ID received from backend
dispatchStreamingStartEvent(assistantMessageId, sessionId);

// When streaming completes
dispatchStreamingCompleteEvent(assistantMessageId, sessionId);
```

<Note>
  These utilities are only needed for Weave Ad Format. See the [Weave Ad Format guide](/platforms/weave-ad-format) for complete integration details.
</Note>

***

## Installation Methods

<AccordionGroup>
  <Accordion title="npm (recommended)">
    ```bash theme={null}
    npm install admesh-ui-sdk@latest
    ```
  </Accordion>

  <Accordion title="Yarn">
    ```bash theme={null}
    yarn add admesh-ui-sdk@latest
    ```
  </Accordion>

  <Accordion title="pnpm">
    ```bash theme={null}
    pnpm add admesh-ui-sdk@latest
    ```
  </Accordion>
</AccordionGroup>

***

## Requirements

<CardGroup cols={2}>
  <Card title="React 16.8+" icon="react">
    Requires React with Hooks support
  </Card>

  <Card title="API Key" icon="key">
    Get your API key from the AdMesh dashboard
  </Card>

  <Card title="TypeScript" icon="code">
    Full TypeScript support included
  </Card>

  <Card title="Modern Browser" icon="browser">
    Supports all modern browsers (Chrome, Firefox, Safari, Edge)
  </Card>
</CardGroup>

***

## TypeScript Support

The SDK is written in TypeScript and includes full type definitions:

```typescript theme={null}
import type {
  AdMeshProviderProps,
  AdMeshRecommendationsProps,
  WeaveAdFormatContainerProps,
  Message
} from 'admesh-ui-sdk';
```

All components and utilities are fully typed for the best developer experience.

***

## Troubleshooting

<AccordionGroup>
  <Accordion title="Recommendations not showing">
    **Check:**

    * API key is valid and provided to `AdMeshProvider`
    * `sessionId` is provided to `AdMeshProvider`
    * Component is wrapped inside `AdMeshProvider`
    * Messages array is not empty (for `AdMeshRecommendations`)
    * Network requests are not blocked by CORS or ad blockers
  </Accordion>

  <Accordion title="TypeScript errors">
    **Solution:**

    * Ensure you're using TypeScript 4.0 or higher
    * Import types explicitly: `import type { Message } from 'admesh-ui-sdk'`
    * Check that your `tsconfig.json` includes `"moduleResolution": "node"`
  </Accordion>

  <Accordion title="Weave Ad Format not detecting links">
    **Check:**

    * You're dispatching `streamingStart` and `streamingComplete` events
    * Events use the assistant message ID (from backend), not user message ID
    * Links are in the correct format (AdMesh tracking URLs)
    * See the [Weave Ad Format troubleshooting guide](/platforms/weave-ad-format#troubleshooting)
  </Accordion>

  <Accordion title="Tracking not working">
    **Note:** Tracking is fully automatic. Do NOT:

    * Manually fire tracking pixels
    * Modify tracking URLs
    * Implement custom tracking logic

    The SDK handles all tracking internally.
  </Accordion>
</AccordionGroup>

***

## Styling & Customization

The AdMesh UI SDK includes a simple, framework-agnostic styling system that ensures your components look clean and consistent—no matter where they're embedded (Next.js, React, Vite, or custom platforms).

### Key Features

<CardGroup cols={2}>
  <Card title="Style Isolation" icon="shield">
    Prevents CSS conflicts with host frameworks like Tailwind or Bootstrap.
  </Card>

  <Card title="Consistent Look" icon="layout">
    Same visual quality across all environments.
  </Card>

  <Card title="Custom Themes" icon="palette">
    Easily adjust colors, borders, and typography.
  </Card>

  <Card title="Light & Dark Modes" icon="sun">
    Built-in theme switching with simple configuration.
  </Card>
</CardGroup>

### Default Styling

By default, the SDK injects its own scoped styles automatically. No CSS import is needed.

```tsx theme={null}
import { AdMeshProvider, AdMeshRecommendations } from 'admesh-ui-sdk';

<AdMeshProvider apiKey="your-api-key" sessionId={sessionId}>
  <AdMeshRecommendations
    messageId={messageId}
    query={userQuery}
    format="tail"
  />
</AdMeshProvider>
```

### Custom Theming

You can customize the appearance by passing a theme to the `AdMeshProvider`:

```tsx theme={null}
import { AdMeshProvider } from 'admesh-ui-sdk';

const customTheme = {
  mode: 'dark',
  primaryColor: '#3b82f6',
  accentColor: '#ffffff',
  borderRadius: '0.5rem',
  fontFamily: 'Inter, sans-serif'
};

<AdMeshProvider
  apiKey="your-api-key"
  sessionId={sessionId}
  theme={customTheme}
>
  <YourApp />
</AdMeshProvider>
```

### Theme Options

| Property          | Type                | Default                         | Description                  |
| ----------------- | ------------------- | ------------------------------- | ---------------------------- |
| `mode`            | `'light' \| 'dark'` | `'light'`                       | Color scheme mode            |
| `primaryColor`    | `string`            | `'#3b82f6'`                     | Primary brand color          |
| `accentColor`     | `string`            | `'#8b5cf6'`                     | Accent color for highlights  |
| `backgroundColor` | `string`            | `'#ffffff'`                     | Background color             |
| `textColor`       | `string`            | `'#1f2937'`                     | Primary text color           |
| `borderRadius`    | `string`            | `'0.5rem'`                      | Border radius for components |
| `fontFamily`      | `string`            | `'system-ui'`                   | Font family                  |
| `shadowMd`        | `string`            | `'0 4px 12px rgba(0,0,0,0.08)'` | Medium shadow                |

### CSS Variables

You can also override AdMesh styling with standard CSS variables:

```css theme={null}
:root {
  --admesh-primary-color: #3b82f6;
  --admesh-border-radius: 10px;
  --admesh-font-family: 'Inter', sans-serif;
  --admesh-shadow-md: 0 4px 12px rgba(0, 0, 0, 0.08);
}
```

### Example Themes

<AccordionGroup>
  <Accordion title="Dark Theme">
    ```tsx theme={null}
    const darkTheme = {
      mode: 'dark',
      primaryColor: '#0ea5e9',
      backgroundColor: '#1f2937',
      textColor: '#f9fafb'
    };

    <AdMeshProvider theme={darkTheme} apiKey="..." sessionId="...">
      <YourApp />
    </AdMeshProvider>
    ```
  </Accordion>

  <Accordion title="Brand Theme">
    ```tsx theme={null}
    const brandTheme = {
      primaryColor: '#6366f1',
      accentColor: '#8b5cf6',
      borderRadius: '0.75rem',
      fontFamily: 'Poppins, sans-serif'
    };

    <AdMeshProvider theme={brandTheme} apiKey="..." sessionId="...">
      <YourApp />
    </AdMeshProvider>
    ```
  </Accordion>

  <Accordion title="Minimal Theme">
    ```tsx theme={null}
    const minimalTheme = {
      primaryColor: '#000',
      backgroundColor: '#fff',
      borderRadius: '0px',
      shadowMd: 'none'
    };

    <AdMeshProvider theme={minimalTheme} apiKey="..." sessionId="...">
      <YourApp />
    </AdMeshProvider>
    ```
  </Accordion>
</AccordionGroup>

### Framework Integration

#### Next.js + Tailwind

AdMesh styles are isolated from Tailwind classes, so you can safely use both:

```tsx theme={null}
import { AdMeshProvider, AdMeshRecommendations } from 'admesh-ui-sdk';

export default function Recommendations() {
  return (
    <AdMeshProvider apiKey={process.env.NEXT_PUBLIC_ADMESH_API_KEY} sessionId={sessionId}>
      <div className="p-4 bg-white rounded-lg">
        <AdMeshRecommendations
          messageId={messageId}
          query={userQuery}
          format="tail"
        />
      </div>
    </AdMeshProvider>
  );
}
```

#### React + Bootstrap

```tsx theme={null}
import { AdMeshProvider, AdMeshRecommendations } from 'admesh-ui-sdk';

export default function App() {
  return (
    <AdMeshProvider apiKey={process.env.REACT_APP_ADMESH_API_KEY} sessionId={sessionId}>
      <div className="container">
        <AdMeshRecommendations
          messageId={messageId}
          query={userQuery}
          format="tail"
        />
      </div>
    </AdMeshProvider>
  );
}
```

### Styling Best Practices

✅ **DO:**

* Use the `theme` prop on `AdMeshProvider` for global styling
* Leverage CSS variables for fine-grained control
* Test your theme in both light and dark modes
* Keep styles consistent with your brand

❌ **DON'T:**

* Directly modify AdMesh component classes (they may change)
* Override internal styles with `!important` (use theme API instead)
* Mix multiple theming approaches (choose one method)

***

## Next Steps

Choose your integration format and follow the detailed guide:

<CardGroup cols={2}>
  <Card title="Tail & Product Format" icon="list" href="/platforms/tail-format">
    Display recommendations in a separate panel

    **Best for:** Separate recommendations UI, simple integration

    **Setup time:** 5-10 minutes
  </Card>

  <Card title="Weave Ad Format" icon="link" href="/platforms/weave-ad-format">
    Embed recommendations directly in LLM responses

    **Best for:** Natural integration, conversational ads

    **Setup time:** 15-20 minutes
  </Card>
</CardGroup>

***
