> For the complete documentation index, see [llms.txt](https://shoppad.gitbook.io/yedric/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://shoppad.gitbook.io/yedric/developers/embedding-widget.md).

# Embedding the Widget

The Yedric widget is a web component, `<yedric-widget>`, that renders a chat panel in Shadow DOM on any page. You add a single script tag for `widget.js`, which registers the custom element and exposes `window.Yedric`.

## Before you start

You need two values from the Yedric dashboard:

1. An **agent ID**: create an agent at **Agents → All agents → New agent** (or use an existing one). The ID is in the URL when you're on the agent's page.
2. A **public widget API key**: open your agent and go to **Widget → Install**. The key starts with `yk_…`. Copy it.

That's enough for a working embed with API-key auth. For per-user chat history, see [Secure Mode](/yedric/developers/secure-mode.md). It also uses the key's **secret** (`yks_…`), which you sign with server-side and never ship to the browser.

## Quick start

The easiest way to generate your embed code is from the Widget page in the dashboard. The Install tab will generate embed code similar to this:

```html
<script src="https://cdn.yedric.ai/widget.js?agent=your_agent_id"></script>
<yedric-widget
  key="yk_your_public_key_here"
  agent="your_agent_id"
></yedric-widget>
```

Pasting this before `</body>` is enough to see the launcher and use the chat. We suggest enabling [Secure Mode](/yedric/developers/secure-mode.md) by using your secret key to generate a signature attribute.

## Design and layout are configured in the dashboard

All design, layout, and behavior settings live in the dashboard under **Widget → Configure**, not on the `<yedric-widget>` element. That includes the theme, colors, fonts, icons, mascot videos, panel width and placement, greeting text, and feature toggles.

Settings you save there are stored with the agent and delivered to the widget automatically along with `widget.js`. You do not add appearance attributes to the embed code, and you do not redeploy your site to restyle the widget: every page picks up your saved configuration the next time it loads.

The element itself only needs a small set of attributes for identity, authentication, and embed-specific plumbing that cannot live in the dashboard. Those are listed below.

## Attribute reference

| Attribute   | Required | Description                                                                                                                                                     |
| ----------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`       | Yes      | Public widget API key (`yk_…`). Sent as `X-Yedric-Key`.                                                                                                         |
| `agent`     | Yes      | Agent ID to use for chat and secure-mode history.                                                                                                               |
| `username`  | No       | End-user id for [secure mode](/yedric/developers/secure-mode.md) (email, UUID, or other stable id). Sent as `X-Yedric-Username`.                                |
| `signature` | No       | `HMAC-SHA256(secret, username)` using the agent key's **secret** (`yks_…`). Sent as `X-Yedric-Signature`. See [Secure Mode](/yedric/developers/secure-mode.md). |
| `name`      | No       | User's display name for personalization (sent as session context).                                                                                              |
| `debug`     | No       | Boolean-like. When truthy, widget `console.log` diagnostics run. Can also be enabled for all embeds in **Widget → Configure → Advanced**.                       |

### Situational attributes

Only needed for specific hosting setups:

| Attribute               | Description                                                                                                                                                                                                                                                                                                                                                                    |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `auth-token`            | Static bearer JWT that is passed to Actions (`Authorization: Bearer …`). For embedded Shopify apps prefer App Bridge, and set it up on the custom tool server so the widget uses App Bridge `idToken()`.                                                                                                                                                                       |
| `shop`                  | Myshopify hostname (e.g. `example-store.myshopify.com`) appended as `?shop=` on API requests for Shopify App Bridge auth. Falls back to the `shop` URL query param or `window.shopify.config.shop`.                                                                                                                                                                            |
| `backend-url`           | Explicit API base URL (`http`/`https`). Only needed when `widget.js` is on a different host than the API.                                                                                                                                                                                                                                                                      |
| `session-id-prefix`     | `widget` (default) or `preview`. Keeps preview traffic separate from production.                                                                                                                                                                                                                                                                                               |
| `resume-session-id`     | Secure mode only. Resume a specific conversation thread by id on load instead of the user's default thread. See [Secure Mode → Carrying a conversation across widget instances](/yedric/developers/secure-mode.md#carrying-a-conversation-across-widget-instances).                                                                                                            |
| `preview-page-url`      | Override `window.location` for page prompt matchUrl/ignoreUrl, suggestion `{URL}` / `{{var}}`, and chat API `siteUrl`.                                                                                                                                                                                                                                                         |
| `parent-origin`         | Target origin for the `postMessage` bridge when the widget is hosted inside an iframe. See [Advanced Configuration](/yedric/developers/advanced-configuration.md#iframe-and-cross-frame-embedding).                                                                                                                                                                            |
| `prompt-suggestion`     | Page-specific text for the top bubble shown beside the closed beacon when **Show Page prompts when beacon is closed** is on. Overrides the **Prompt suggestion** configured in the dashboard for this embed only. It cannot turn the feature on by itself. See [Advanced Configuration](/yedric/developers/advanced-configuration.md#prompt-suggestions-on-the-closed-beacon). |
| `reopen-on-page-change` | Boolean-like. Reopen the panel on the next page, with the same conversation, when the visitor follows a link with the chat open. Overrides the **Re-open when page changes** setting for this embed. See [Advanced Configuration](/yedric/developers/advanced-configuration.md#re-open-when-page-changes).                                                                     |
| `fab-draggable`         | Set to `"false"` to stop visitors dragging the beacon to another corner on this embed. Any other value, or omitting it, leaves dragging on. See [Advanced Configuration](/yedric/developers/advanced-configuration.md#draggable-beacon).                                                                                                                                       |
| `navigate-allow`        | Extra origins the assistant's built-in navigate action may send the visitor to, separated by spaces or commas (`https://docs.example.com https://help.example.com`). The embedding page's own origin is always allowed; `http`/`https` only. See [Advanced Configuration](/yedric/developers/advanced-configuration.md#letting-the-assistant-navigate-to-other-origins).       |

Boolean-like attributes (`debug`, `reopen-on-page-change`) accept `""`, `"true"`, `"1"`, or `"yes"` as truthy; `"false"`, `"0"`, `"no"` as falsy. Omitting the attribute is the same as false, except that omitting `reopen-on-page-change` defers to the dashboard setting. `fab-draggable` is the reverse: only `"false"` has an effect.

## Additional customizations

Everything else is configured per agent in **Widget → Configure** and applies to every embed of that agent once you click **Save**. Settings are grouped into the following cards. Use the **Preview** tab to see changes live before publishing.

### General

| Setting                                 | Description                                                                                                                                                                                                                                                                                                        |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Theme                                   | Yeti, Light, or Dark. Switching themes resets colors, icons, and mascot videos to the theme's defaults.                                                                                                                                                                                                            |
| Title                                   | Shown in the panel header and the default beacon tooltip.                                                                                                                                                                                                                                                          |
| Side (beacon & panel)                   | Left or Right. The open panel docks to the same edge as the beacon. Visitors can drag the beacon to another corner, remembered per agent in their browser; opt out with `fab-draggable="false"`.                                                                                                                   |
| Default state                           | Open, or Closed (beacon only) until the user or code opens it. On viewports 640px and narrower an Open embed starts closed, since the panel would fill the screen. Exceptions: `fab="false"` embeds (no beacon to reopen with), `resume-session-id` handoffs, an interrupted live chat, and the dashboard preview. |
| Show Page prompts when beacon is closed | Shown when Default state is Closed. Shows the current page's Page prompts as clickable bubbles beside the closed beacon; clicking one opens the chat and sends the prompt. Dismissed bubbles return after an hour, and the beacon tooltip is suppressed while this is on.                                          |
| Prompt suggestion                       | Shown when the box above is checked. Optional text for the top bubble, shown with the assistant's avatar; line breaks become separate lines. The cluster shows at most four bubbles in total. Override per page with `prompt-suggestion`.                                                                          |
| Re-open when page changes               | If a visitor follows a link with the chat open, it opens again on the next page with the same conversation. Off by default. Override per embed with `reopen-on-page-change`.                                                                                                                                       |
| Hide beacon                             | When the panel is closed, no beacon button is shown. Open the widget with `Yedric.open()` or your own control.                                                                                                                                                                                                     |
| Beacon position                         | Top, Middle, or Bottom of the viewport edge.                                                                                                                                                                                                                                                                       |

### Features

| Setting                     | Description                                                                                                                                                                                                                                                                                                         |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| File uploads                | Show a paperclip button so users can attach files to their messages.                                                                                                                                                                                                                                                |
| Microphone (speech-to-text) | Show a mic button so users can dictate messages.                                                                                                                                                                                                                                                                    |
| Live chat                   | Show an escalation button so visitors can reach your team. With the **Built-in** provider it opens Yedric's own chat panel ([live chat](/yedric/going-further/live-chat.md)). With **External** it fires the `human_support` event so the host page can open your chat provider, a support form, or a call.         |
| Response voting             | Show up/down vote buttons on the latest response from the Assistant. Fires the `response_vote` event.                                                                                                                                                                                                               |
| Show tool activity          | Show the step-by-step "I'm running…" tool status lines as the assistant works. Steps render in the reply at the point where they ran, so the step currently running sits below the text written so far. Turn off to hide all tool activity from visitors; typing dots show while a hidden tool runs. On by default. |

### Mascot

| Setting         | Description                                                                                                                                                                                                                                                                                                                                                                                                           |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Beacon icon     | Image used as the beacon button icon, plus an optional hover variant.                                                                                                                                                                                                                                                                                                                                                 |
| Agent chat icon | Assistant avatar shown on each chat message. Defaults to the beacon icon.                                                                                                                                                                                                                                                                                                                                             |
| User Chat icon  | Avatar beside the user's messages: initials from their name or email, or their Gravatar with a fallback style.                                                                                                                                                                                                                                                                                                        |
| Beacon tooltip  | Hover text on the beacon. Supports context variables. Hidden while **Show Page prompts when beacon is closed** is on, since the bubbles take its place.                                                                                                                                                                                                                                                               |
| Videos          | Optional mascot video clips: Waving (welcome), Thinking (loading), Thumbs up, and Presenting (after reply), plus an optional placeholder image shown when no clip is playing. Each field has an **Upload** button (MP4 or WebM, up to 10 MB; PNG, JPEG, GIF, WebP, or AVIF for the placeholder) or takes a URL to a file you host. A configured Waving clip plays on open by itself; nothing shows if no clip is set. |

### Display

| Setting                      | Description                                                                                                              |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| Panel width (open)           | Any CSS length. On viewports 640px and narrower the panel takes the full width regardless.                               |
| Border style                 | Line, Shadow, or Rounded.                                                                                                |
| Suggestion style             | Layout for starter suggestions: Stacked, Centered, List rows, Chips, Icon cards, Minimal links, or Suggested panel.      |
| Prompt placeholder text      | Placeholder shown in the message input.                                                                                  |
| Prompt textbox border radius | Corner radius of the message input.                                                                                      |
| Button border radius         | Corner radius of buttons.                                                                                                |
| Font family / Base font size | Typography for the panel.                                                                                                |
| Greeting                     | Optional headline above the starter suggestions when the chat is empty. Supports context variables like the user's name. |
| Greeting description         | Optional secondary line below the greeting.                                                                              |

The Display card also contains the full color palette, grouped as:

* **Base theme**: Primary / accent, Panel background, Body text, Panel border
* **Title bar (header)**: Header height, Title bar background, Title bar border, Title bar text, Title bar icons
* **Buttons**: Submit (send) button background and icon, Icon color, Icon button background and hover
* **Prompt input**: Input background, Prompt textbox border, Prompt area background and border
* **Suggestions**: Suggestion button background, Suggestion button background (hover), Suggestion border, Suggestion text
* **Avatar & message bubble**: User avatar background, Assistant avatar & beacon background (also paints the tile behind the beacon icon, so the launcher and the chat avatar match), User text background, Assistant text background, User message text, Assistant message text
* **Greeting**: Greeting text color, Greeting description text color

### Advanced

| Setting                                      | Description                                                            |
| -------------------------------------------- | ---------------------------------------------------------------------- |
| Features (comma-separated)                   | Feature flags for the embed. Defaults to `chat,mcp`.                   |
| Add margin to host body when sidebar is open | Shifts the host page content instead of overlaying it with a backdrop. |
| Debug mode (in console log messages)         | Enables widget console diagnostics on every embed.                     |

## Embed snippets

### Basic

```html
<script src="https://cdn.yedric.ai/widget.js?agent=agt_123"></script>
<yedric-widget key="yk_abc…" agent="agt_123"></yedric-widget>
```

### Open from your own UI

Turn on **Hide beacon** and set **Default state** to Closed in **Widget → Configure → General**, then open the panel programmatically:

```html
<yedric-widget key="yk_abc…" agent="agt_123"></yedric-widget>

<button onclick="window.Yedric.open('How can I track my order?')">Ask about shipping</button>
```

### Secure mode (server-rendered)

```html
<!-- signature computed server-side: HMAC-SHA256(yks_secret, username), hex -->
<yedric-widget
  key="yk_abc…"
  agent="agt_123"
  username="jannette.parks@yedric.ai"
  signature="a1b2c3…"
></yedric-widget>
```

See [Secure Mode](/yedric/developers/secure-mode.md) for server-side signing examples in Node, PHP, and SubtleCrypto.

### Follow the visitor between pages, with a page-specific prompt

Reopen the chat on the next page and replace the dashboard's **Prompt suggestion** with one written for this page:

```html
<yedric-widget
  key="yk_abc…"
  agent="agt_123"
  reopen-on-page-change="true"
  prompt-suggestion="Need help choosing a plan?"
></yedric-widget>
```

### Let the assistant navigate to your docs site

The assistant can only send visitors to pages on the embedding site unless you list other origins:

```html
<yedric-widget
  key="yk_abc…"
  agent="agt_123"
  navigate-allow="https://docs.example.com https://help.example.com"
></yedric-widget>
```

### Shopify admin (embedded app)

The auth token for Shopify App Bridge is loaded from the custom tool server when App Bridge auth is enabled there, so you do not need to set `auth-token` manually. Theme, colors, greeting, and mascot videos come from **Widget → Configure**.

```html
<script src="https://cdn.yedric.ai/widget.js?agent=agt_123"></script>
<yedric-widget
  key="yk_abc…"
  agent="agt_123"
  username="example-store.myshopify.com"
  signature="<?= hash_hmac('sha256', $shopUuid, $yedricSecret) ?>"
></yedric-widget>
```

## Common embedding mistakes

Pulled from production integrations that came in with subtle breakage.

1. **Duplicate attributes.** The browser keeps the last value of a repeated attribute, so dropping a hardcoded `key="yk_…"` next to a server-rendered one silently wins, wrong key. Write each attribute exactly once.
2. **Stray quotes.** A typo like `signature="…""` has a trailing `"`, which swallows every attribute after it on the same line until the next `>`. Scan your rendered HTML, not just the template.
3. **Styling with attributes.** Appearance attributes on the element are not the supported way to style the widget. Configure design and layout in **Widget → Configure** so every page stays in sync with your saved settings.
4. **Secrets in HTML.** Never render the `yks_…` secret in markup or JavaScript. Only render `signature` (the HMAC output). See [Secure Mode](/yedric/developers/secure-mode.md).
5. **Wrong `widget.js` origin.** If your API is at `https://api.example.com/yedric`, either serve `widget.js` from `https://api.example.com/yedric/widget.js` (auto-inferred) or add `backend-url="https://api.example.com/yedric"` to the element when you must serve from a CDN.
6. **Using `key` from React JSX.** `key` is reserved in React. Use a ref and `setAttribute('key', …)`, or pass it via `setConfig({ yedricKey })`.

   ```jsx
   import { useEffect, useRef } from 'react';

   export function YedricWidget({ apiKey, agentId }) {
     const ref = useRef(null);
     useEffect(() => {
       if (ref.current) {
         ref.current.setAttribute('key', apiKey);
       }
     }, [apiKey]);
     return <yedric-widget ref={ref} agent={agentId} />;
   }
   ```

## Troubleshooting

If you see nothing on the page, open the browser console and check for these:

| Symptom                                              | Likely cause                                                                                                                   | Fix                                                                                                                                                                                                                                            |
| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /widget.js` returns 404                         | Wrong script URL or widget bundle not deployed alongside the API                                                               | Serve `widget.js` from the same origin+path as your API.                                                                                                                                                                                       |
| `[Yedric] No <yedric-widget> found in the document.` | You called `window.Yedric.open()` before the element was added, or the element isn't on the page                               | Add the `<yedric-widget>` element before calling any `Yedric.*` method.                                                                                                                                                                        |
| `401 Invalid Yedric Key or domain not allowed`       | Wrong `key`; origin not in the key's `allowedDomains`; or the request carried no `Origin`/`Referer` header at all              | Check the key value matches the dashboard; add your origin to `allowedDomains` (or clear the list). A domain-restricted key now **fails closed** when there is no origin header, so non-browser callers need a key with no domain restriction. |
| `401 Invalid signature`                              | `signature` doesn't match `HMAC-SHA256(secret, username)`                                                                      | Ensure the `username` you sign matches the `username` attribute byte-for-byte. See [Secure Mode](/yedric/developers/secure-mode.md).                                                                                                           |
| `400 agentId required`                               | The `agent` attribute wasn't set                                                                                               | Add `agent="your-agent-id"` to the element.                                                                                                                                                                                                    |
| Widget loads but chat returns nothing                | Assistant has no model, API keys are missing from Settings                                                                     | In the dashboard → Settings, set at least one provider key (Google/OpenAI/Anthropic).                                                                                                                                                          |
| React: `key` attribute seems to be ignored           | React treats `key` as a reserved prop and strips it from the DOM                                                               | Use a ref and `el.setAttribute('key', value)`, or pass it via `el.setConfig({ yedricKey })`.                                                                                                                                                   |
| `Yedric.open()` doesn't fire a message               | Default state set to Closed combined with passing a prompt works fine, but calling from SPA before widget mount fails silently | Guard with `typeof window.Yedric !== 'undefined'`. See [Advanced Configuration](/yedric/developers/advanced-configuration.md#programmatically-open-the-sidebar).                                                                               |
| Widget looks unstyled or ignores your changes        | Configure changes were made but not published                                                                                  | Click **Save** in **Widget → Configure**; the widget picks up the saved settings on the next page load.                                                                                                                                        |

Enable `debug="true"` to get verbose logs in the console: route changes, matched site settings, client-tool delegation, and secure-mode state.

## What's next

* [Secure Mode](/yedric/developers/secure-mode.md): per-user sessions with HMAC verification
* [Advanced Configuration](/yedric/developers/advanced-configuration.md): iframe embedding, client-side custom HTTP tools, programmatic open, closed-beacon prompt suggestions, cross-page reopen, navigation origins
* [JavaScript API](/yedric/developers/javascript-api.md): `window.Yedric.open()`, events
