> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.flockx.io/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.flockx.io/_mcp/server.

# Engaging Visitors: Deploying Your AI Agent on Your Website

> Provide instant support on your website with your AI agent

Deploy your AI agent directly on your website to provide instant support, answer questions, and engage visitors—all with a customizable, always-available chat experience.

### Connect your Agent to your Website's Chat Widget

## Quick Start (2 Minutes)

Add these two elements to your website, just before the closing `</body>` tag:

```html
<!-- Step 1: Configure your widget -->
<script>
  window.__CHAT_WIDGET_CONFIG = {
    agentId: "YOUR_AGENT_ID_HERE",
    widgetButtonImageUrl: "https://your-site.com/path/to/avatar.jpg",
  };
</script>

<!-- Step 2: Load the widget -->
<script src="https://widget-cdn.flockx.io/flockx-chat.min.js" async></script>
```

That's it! A chat bubble will appear in the bottom-right corner of your website.

## Configuration Options

| Property               | Type          | Required | Description                             |
| ---------------------- | ------------- | -------- | --------------------------------------- |
| `agentId`              | string (UUID) | ✅ Yes    | Your Flockx agent's unique identifier   |
| `widgetButtonImageUrl` | string (URL)  | ❌ No     | Custom avatar image for the chat button |

## Step 1: Access Your Agent Settings

1. Log in to your Flockx dashboard at [flockx.io](https://flockx.io).
2. Select the specific agent you want to integrate with your website.
3. Click on the **Settings** tab in the agent management panel.

## Step 2: Locate the Chat Widget Section

1. Scroll down to find the **Chat Widget** section.
2. This section handles all website-based deployment options.

## Step 3: Upgrade to Enterprise (If Needed)

If you haven't yet subscribed to the Enterprise plan:

1. Click **Upgrade to Enterprise** within the Chat Widget section.
2. You'll be taken to the **package selection screen**.
3. Select a plan and proceed to the **Stripe payment page**.
4. Complete your billing information and submit.
5. You'll be automatically redirected to your settings dashboard upon completion.

## Step 4: Configure Your Widget

Once upgraded:

1. Enable the **Chat Widget** via toggle.
2. Click **Configure** to:
   * Customize widget appearance (color, size, placement)
   * Set behavior rules (when to open, how it greets)
   * Craft a custom welcome message
3. A **Flockx representative** will assist you with setup and design preferences.

## Step 5: Add the Widget to Your Website

### Finding Your Agent ID

1. In your Flockx dashboard, navigate to **Agents**
2. Click on your agent
3. Copy the **Agent ID** from the agent settings or URL (UUID format like `f4393fac-1e23-4549-85fe-cd5b6cafff39`)

### Framework-Specific Examples

#### Next.js

In your root layout (`src/app/layout.tsx`):

```typescript
import Script from 'next/script';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        {children}
        
        {/* Flockx Chat Widget Configuration */}
        <Script id="flockx-chat-config" strategy="beforeInteractive">
          {`
            window.__CHAT_WIDGET_CONFIG = {
              agentId: "YOUR_AGENT_ID_HERE",
              widgetButtonImageUrl: "/images/your-avatar.jpg",
            };
          `}
        </Script>
        
        {/* Flockx Chat Widget Script */}
        <Script 
          src="https://widget-cdn.flockx.io/flockx-chat.min.js"
          strategy="lazyOnload"
        />
      </body>
    </html>
  );
}
```

#### Astro

In your base layout (`src/layouts/BaseLayout.astro`):

```astro
<html lang="en">
  <head>
    <!-- Your head content -->
  </head>
  <body>
    <main>
      <slot />
    </main>
    
    <!-- Flockx Chat Widget -->
    <script is:inline>
      window.__CHAT_WIDGET_CONFIG = {
        agentId: "YOUR_AGENT_ID_HERE",
        widgetButtonImageUrl: "/images/your-avatar.jpg",
      };

      (function () {
        const script = document.createElement("script");
        script.src = "https://widget-cdn.flockx.io/flockx-chat.min.js";
        script.async = true;
        document.body.appendChild(script);
      })();
    </script>
  </body>
</html>
```

#### React

In your `public/index.html`:

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Your head content -->
  </head>
  <body>
    <div id="root"></div>
    
    <!-- Flockx Chat Widget -->
    <script>
      window.__CHAT_WIDGET_CONFIG = {
        agentId: "YOUR_AGENT_ID_HERE",
        widgetButtonImageUrl: "/your-avatar.jpg",
      };
    </script>
    <script src="https://widget-cdn.flockx.io/flockx-chat.min.js" async></script>
  </body>
</html>
```

#### Plain HTML

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <title>My Website</title>
</head>
<body>
  <h1>Welcome to my website</h1>
  
  <!-- Add at the end of body -->
  <script>
    window.__CHAT_WIDGET_CONFIG = {
      agentId: "YOUR_AGENT_ID_HERE",
      widgetButtonImageUrl: "https://example.com/avatar.jpg",
    };
  </script>
  <script src="https://widget-cdn.flockx.io/flockx-chat.min.js" async></script>
</body>
</html>
```

## Best Practices

### Avatar Image Recommendations

* **Format**: Use `.webp` for best performance, or `.jpg`/`.png`
* **Size**: Recommended 80x80px to 200x200px
* **Shape**: The widget displays it as a circle, so center your subject
* **Hosting**: Use your own domain or a CDN for reliability

### Performance Optimization

The widget script loads asynchronously and won't block your page rendering. For additional optimization, you can delay loading until user interaction:

```javascript
// Load only after user interaction (click, scroll, etc.)
document.addEventListener('scroll', function loadWidget() {
  window.__CHAT_WIDGET_CONFIG = {
    agentId: "YOUR_AGENT_ID_HERE",
  };
  
  const script = document.createElement('script');
  script.src = 'https://widget-cdn.flockx.io/flockx-chat.min.js';
  document.body.appendChild(script);
  
  // Remove listener after first trigger
  document.removeEventListener('scroll', loadWidget);
}, { once: true });
```

### Agent Preparation

Before embedding, ensure your agent is configured with:

* ✅ Clear personality and response style
* ✅ Relevant knowledge base documents
* ✅ Welcome message for first-time visitors
* ✅ Appropriate response length settings

## Troubleshooting Tips

* **Widget not appearing?** Check browser console for JavaScript errors. Verify your agent ID is correct (UUID format).
* **Enterprise not activated?** Ensure payment completed successfully and refresh your settings page.
* **Widget appears but no responses?** Test your agent in the Flockx dashboard first. Ensure it's active and not paused.
* **Customization changes not visible?** Clear your browser cache or test in incognito mode.
* **Need hands-on help?** Reach out to your assigned rep or contact [contact@flockx.io](mailto:contact@flockx.io)

## Security Considerations

* The widget uses secure WebSocket connections (`wss://`)
* Agent ID is public (visible in page source)—this is expected and safe
* API authentication happens server-side via Flockx infrastructure
* No sensitive credentials should be placed in client-side code

## Benefits of Website Integration

* Provide real-time AI-powered support to your website visitors
* Answer frequently asked questions instantly
* Guide users through your products or services
* Collect initial information before human handoff (if needed)
* Operate 24/7 without staffing concerns

---

## JavaScript API

The Flockx widget exposes a global `FlockxWidget` object for programmatic control. This is useful for:

* Opening the widget when users click a custom button
* Sending messages based on page context
* Tracking conversations in your analytics
* Personalizing responses with user data

### Methods

| Method                           | Description                          |
| -------------------------------- | ------------------------------------ |
| `FlockxWidget.open()`            | Open the chat widget                 |
| `FlockxWidget.close()`           | Close the chat widget                |
| `FlockxWidget.toggle()`          | Toggle the widget open/closed        |
| `FlockxWidget.sendMessage(text)` | Send a message programmatically      |
| `FlockxWidget.setUser(userData)` | Set user context for personalization |
| `FlockxWidget.destroy()`         | Remove the widget from the page      |

### Events

Listen for widget events to integrate with your application:

| Event                     | Payload                      | Description             |
| ------------------------- | ---------------------------- | ----------------------- |
| `flockx:ready`            | `{}`                         | Widget loaded and ready |
| `flockx:open`             | `{}`                         | Widget opened           |
| `flockx:close`            | `{}`                         | Widget closed           |
| `flockx:message:sent`     | `{ text, timestamp }`        | User sent a message     |
| `flockx:message:received` | `{ text, agent, timestamp }` | Agent responded         |

### Example: Advanced Integration

```javascript
// Wait for widget to be ready
window.addEventListener('flockx:ready', () => {
  console.log('Flockx widget is ready!');
  
  // Set user context for personalized responses
  FlockxWidget.setUser({
    name: 'Alex Creator',
    email: 'alex@example.com',
    plan: 'pro',
    interests: ['podcasting', 'content creation']
  });
});

// Track messages in your analytics
window.addEventListener('flockx:message:sent', (event) => {
  analytics.track('chat_message_sent', {
    text: event.detail.text,
    page: window.location.pathname
  });
});

window.addEventListener('flockx:message:received', (event) => {
  analytics.track('chat_message_received', {
    agent: event.detail.agent,
    responseTime: event.detail.responseTime
  });
});

// Open widget when clicking a custom button
document.getElementById('help-button').addEventListener('click', () => {
  FlockxWidget.open();
});

// Send contextual message based on page
if (window.location.pathname.includes('/pricing')) {
  window.addEventListener('flockx:open', () => {
    FlockxWidget.sendMessage('I have a question about pricing');
  }, { once: true });
}
```

### Example: Custom Trigger Button

Replace the default floating button with your own:

```html
<!-- Hide the default widget button -->
<script>
  window.__CHAT_WIDGET_CONFIG = {
    agentId: "YOUR_AGENT_ID",
    hideButton: true  // Hide default floating button
  };
</script>
<script src="https://widget-cdn.flockx.io/flockx-chat.min.js" async></script>

<!-- Your custom button -->
<button id="chat-with-ai" class="my-custom-button">
  Chat with our AI Team
</button>

<script>
  document.getElementById('chat-with-ai').addEventListener('click', () => {
    FlockxWidget.open();
  });
</script>
```

---

## Full Configuration Options

Here's a complete list of configuration options:

```javascript
window.__CHAT_WIDGET_CONFIG = {
  // Required
  agentId: "YOUR_AGENT_ID",  // UUID of your Flockx agent
  
  // Appearance
  widgetButtonImageUrl: "/avatar.jpg",  // Custom avatar image
  widgetButtonSize: 60,                  // Button size in pixels (default: 60)
  position: "bottom-right",              // "bottom-right" | "bottom-left"
  theme: "auto",                         // "light" | "dark" | "auto"
  primaryColor: "#6A67FF",               // Accent color (hex)
  
  // Branding
  headerTitle: "Chat with us",           // Header text when open
  inputPlaceholder: "Type a message...", // Input placeholder text
  welcomeMessage: "Hi! How can I help?", // First message from agent
  
  // Behavior
  hideButton: false,                     // Hide default floating button
  autoOpen: false,                       // Auto-open on page load
  autoOpenDelay: 5000,                   // Delay before auto-open (ms)
  
  // Advanced
  persistSession: true,                  // Remember conversation across pages
  enableSounds: true,                    // Play notification sounds
  enableNotifications: false,            // Browser notifications (requires permission)
  
  // Analytics
  onReady: function() {},                // Callback when widget is ready
  onOpen: function() {},                 // Callback when widget opens
  onClose: function() {},                // Callback when widget closes
  onMessageSent: function(message) {},   // Callback when user sends message
  onMessageReceived: function(message) {} // Callback when agent responds
};
```

---

## Use Cases for Creative Professionals

### Podcasters

```javascript
window.__CHAT_WIDGET_CONFIG = {
  agentId: "YOUR_AGENT_ID",
  welcomeMessage: "Hey! I can help you find episodes, get show notes, or answer questions about our podcast. What are you looking for?",
  headerTitle: "Podcast Assistant"
};
```

### Artists & Designers

```javascript
window.__CHAT_WIDGET_CONFIG = {
  agentId: "YOUR_AGENT_ID",
  welcomeMessage: "Welcome to my studio! I can help with commission inquiries, portfolio questions, or booking information.",
  headerTitle: "Studio Assistant"
};
```

### Writers & Bloggers

```javascript
window.__CHAT_WIDGET_CONFIG = {
  agentId: "YOUR_AGENT_ID",
  welcomeMessage: "Thanks for visiting! I can help you find articles, answer questions about my work, or discuss collaboration opportunities.",
  headerTitle: "Content Assistant"
};
```

### Musicians

```javascript
window.__CHAT_WIDGET_CONFIG = {
  agentId: "YOUR_AGENT_ID",
  welcomeMessage: "Hey there! I can help with booking inquiries, merchandise, or finding information about upcoming shows.",
  headerTitle: "Music Assistant"
};
```

---

## Embedding Multiple Agents (AI Team)

For advanced use cases, you can embed multiple specialized agents:

```javascript
// Example: Different agents for different pages
const agentConfig = {
  '/support': 'support-agent-uuid',
  '/sales': 'sales-agent-uuid',
  '/booking': 'booking-agent-uuid',
  default: 'general-agent-uuid'
};

const currentPath = window.location.pathname;
const agentId = Object.keys(agentConfig).find(path => 
  currentPath.includes(path)
) ? agentConfig[Object.keys(agentConfig).find(path => 
  currentPath.includes(path))] : agentConfig.default;

window.__CHAT_WIDGET_CONFIG = {
  agentId: agentId,
  // ... other config
};
```

---

## Analytics Integration

### Google Analytics 4

```javascript
window.addEventListener('flockx:message:sent', (e) => {
  gtag('event', 'chat_message', {
    event_category: 'engagement',
    event_label: 'user_message',
    value: 1
  });
});

window.addEventListener('flockx:message:received', (e) => {
  gtag('event', 'chat_response', {
    event_category: 'engagement',
    event_label: 'ai_response',
    value: 1
  });
});
```

### Segment

```javascript
window.addEventListener('flockx:message:sent', (e) => {
  analytics.track('Chat Message Sent', {
    text: e.detail.text,
    page: window.location.pathname
  });
});
```

---

## Mobile Considerations

The widget is fully responsive. On mobile devices:

* The widget opens as a full-screen overlay
* Touch interactions are optimized
* Keyboard handling is automatic

For mobile-specific configuration:

```javascript
const isMobile = window.innerWidth < 768;

window.__CHAT_WIDGET_CONFIG = {
  agentId: "YOUR_AGENT_ID",
  widgetButtonSize: isMobile ? 50 : 60,
  position: isMobile ? "bottom-right" : "bottom-right"
};
```

---

## Accessibility

The widget follows WCAG 2.1 guidelines:

* Full keyboard navigation support
* Screen reader compatible
* Focus management
* High contrast support

To enable additional accessibility features:

```javascript
window.__CHAT_WIDGET_CONFIG = {
  agentId: "YOUR_AGENT_ID",
  a11y: {
    announceMessages: true,  // Announce new messages to screen readers
    highContrast: false      // Force high contrast mode
  }
};
```