> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-flutter-sdk-mark-as-unread.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Add CometChat UI Kit Builder Widget to Shopify

> Learn how to embed the CometChat UI Kit Builder widget into your Shopify store using Liquid templates, theme settings, or Online Store 2.0 app blocks.

You can integrate the **CometChat UI Kit Builder widget** directly into your Shopify store to enable real-time chat. Once installed, it will:

* Load the UI Kit Builder bundle on page load
* Initialize CometChat with your App ID, Region & Auth Key
* Automatically log in each visitor (using their Shopify `customer.id` or “guest”)
* Launch a docked chat UI on every page

***

## What You’ll Build

A persistent, docked chat widget in your Shopify theme—fully configurable via Theme Settings or a snippet/app block.

***

## Quick Steps to Embed CometChat Widget

<Steps>
  <Step title="Register on CometChat & Gather Your Keys">
    Before you start, sign up at the [CometChat Dashboard](https://app.cometchat.com/) and create an app. Copy:

    * **App ID**
    * **Region**
    * **Auth Key**
  </Step>

  <Step title="Paste the CometChat Embed Block">
    1. In Shopify Admin, go to **Online Store → Themes → … → Edit code**.
    2. Open **layout/theme.liquid** (or the snippet/section where you want the widget).
    3. Near `</body>`, paste the full block below. It loads the SDK, injects Shopify customer data, and initializes the widget:

    ```liquid theme={null}
    <div id="cometChatMount"></div>

    <!-- Load CometChat Embed SDK -->
    <script defer src="https://cdn.jsdelivr.net/npm/@cometchat/chat-embed@1.x.x/dist/main.js"></script>

    <!-- Shopify Customer Info (auto-filled when accounts are enabled) -->
    <script>
      window.CURRENT_USER_ID = {{ customer.id | default: '' | json }};
      window.CURRENT_USER_NAME = {{ customer.first_name | default: '' | json }};
    </script>

    <!-- CometChat Initialization -->
    <script>
      const COMETCHAT_CREDENTIALS = {
        appID: "YOUR_APP_ID",
        appRegion: "YOUR_APP_REGION",
        authKey: "YOUR_APP_AUTH_KEY", // Must be App Auth Key
      };

      // Detect or fallback to guest user
      const currentUserId =
        window.CURRENT_USER_ID !== null && window.CURRENT_USER_ID !== undefined
          ? window.CURRENT_USER_ID.toString().trim()
          : "";
      const currentUserName =
        window.CURRENT_USER_NAME !== null && window.CURRENT_USER_NAME !== undefined
          ? window.CURRENT_USER_NAME.toString().trim()
          : "";

      const uid = currentUserId.length
        ? currentUserId.replace(/\W+/g, "-")
        : "guest_" + Date.now();
      const name = currentUserName.length ? currentUserName : "Guest User";

      const COMETCHAT_LAUNCH_OPTIONS = {
        targetElementID: "cometChatMount",
        isDocked: true,
        width: "700px",
        height: "500px",
      };

      window.addEventListener("DOMContentLoaded", () => {
        CometChatApp.init(COMETCHAT_CREDENTIALS)
          .then(() => {
            const user = new CometChatApp.CometChat.User(uid);
            user.setName(name);
            return CometChatApp.createOrUpdateUser(user);
          })
          .then(() => CometChatApp.login({ uid }))
          .then(() => CometChatApp.launch(COMETCHAT_LAUNCH_OPTIONS))
          .catch(() => {});
      });
    </script>
    ```
  </Step>

  <Step title="Turn on Customer Accounts (recommended)">
    `{{ customer.id }}` and `{{ customer.first_name }}` only populate when Shopify customer accounts are enabled and the visitor is logged in.

    1. In Shopify Admin, go to **Settings → Customer accounts**.
    2. Choose **Classic customer accounts → Optional** (or **Required**) and save.
    3. Log in as a test customer, reload your storefront, and confirm the widget now shows the real shopper name. If no one is logged in, the script safely falls back to `guest_<timestamp>`.
  </Step>

  <Step title="(Optional) Expose Credentials in Theme Settings">
    To let non-developers manage credentials from the Shopify Theme Editor, add this section in **config/settings\_schema.json** (just before the final `]`):

    ```jsonc theme={null}
    ,
    {
      "name": "CometChat Settings",
      "settings": [
        {
          "type": "text",
          "id": "cometchat_app_id",
          "label": "CometChat App ID",
          "default": "YOUR_APP_ID"
        },
        {
          "type": "text",
          "id": "cometchat_app_region",
          "label": "CometChat App Region",
          "default": "YOUR_REGION"
        },
        {
          "type": "text",
          "id": "cometchat_auth_key",
          "label": "CometChat Auth Key",
          "default": "YOUR_AUTH_KEY"
        }
      ]
    }
    ```
  </Step>

  <Step title="(Advanced) Use an Online Store 2.0 App Block">
    If your theme supports Shopify 2.0 app blocks, you can make a reusable section:

    1. **Online Store → Themes → Edit code**
    2. Under **Sections**, click **Add a new section** → `cometchat-widget.liquid`
    3. Paste the snippet from the previous step into that file.
    4. Save, then add it in **Customize theme** under **App embeds** or as a section on any template:
       ```liquid theme={null}
       {% section 'cometchat-widget' %}
       ```
  </Step>
</Steps>

***

## Advanced JavaScript Controls

The embed works out of the box. Use the helpers below only if you need to open a specific chat, listen for widget events, or change settings on the fly.

### Before you follow advanced setup steps

1. Keep the standard widget snippet (from the Integration guide) on your page.
2. Add another `<script type="module">` right after it or inside your site builder’s “custom code” area.
3. Wrap your code in `window.addEventListener("DOMContentLoaded", () => { ... })` so it runs after the widget loads.
4. Replace placeholder text such as `UID`, `GUID`, and `LANGUAGE_CODE` with your real values.

When the widget is ready, it exposes a global helper named `CometChatApp`. Every example below shows a tiny recipe you can paste inside the script mentioned above.

### Open a chat or start a call

Use these helpers when you want the widget to jump straight to a person/group or begin a call. Drop the snippet inside your custom script and replace `UID`/`GUID` with real IDs from your CometChat app.

```js theme={null}
// Open chat with a specific person
CometChatApp.chatWithUser("UID");

// Open chat with a specific group
CometChatApp.chatWithGroup("GUID");

// Start a call with a person or a group
CometChatApp.callUser("UID");
CometChatApp.callGroup("GUID");

// Toggle extra UI bits
CometChatApp.showGroupActionMessages(true); // Show join/leave messages
CometChatApp.showDockedUnreadCount(true);   // Show unread badge on docked bubble
```

### Listen for widget events

Run your own code when something happens inside the widget—new message, docked bubble opened, or someone switching chats. Keep the event names as shown; just change what happens inside each arrow function.

```js theme={null}
// Fire when a new message arrives
CometChatApp.uiEvent("onMessageReceived", (message) => {
  console.log("New message:", message);
});

// Fire when the docked bubble opens or closes
CometChatApp.uiEvent("onOpenChat", () => console.log("Chat opened"));
CometChatApp.uiEvent("onCloseChat", () => console.log("Chat closed"));

// Fire when the user switches between conversations
CometChatApp.uiEvent("onActiveChatChanged", (chat) => {
  console.log("Now viewing:", chat);
});
```

### Create/Update users on the fly

* This will only work with authKey

If you collect names, avatars, or profile links on your site, you can push them straight into CometChat.
Replace the placeholders and run the snippet after the widget loads.

```js theme={null}
// Create or update a user
const user = new CometChatApp.CometChat.User("UID");
user.setName("User Name");
user.setAvatar("https://example.com/avatar.png");
user.setLink("https://example.com/profile");

CometChatApp.createOrUpdateUser(user).then((result) => {
  console.log("User saved:", result);
});
```

### Create/Update groups on the fly

If you want to create groups directly from your page, use this snippet. Replace the placeholders and run the snippet after the widget loads.

```js theme={null}
// Create or update a group
const group = new CometChatApp.CometChat.Group("GUID", "GROUP_NAME", "public");

CometChatApp.createOrUpdateGroup(group).then((result) => {
  console.log("Group saved:", result);
});
```

### Log users in or out with code

Use an auth token if you have a backend, or fall back to a plain UID for quick tests. Run these helpers after the widget loads.

```js theme={null}
// Sign in with a secure auth token from your server
CometChatApp.login({ authToken: "USER_AUTH_TOKEN" });

// ...or sign in directly with a UID (less secure, but fast for demos)
CometChatApp.login({ uid: "UID" });

// Sign the current user out
CometChatApp.logout();

// Listen for logout so you can clean up your UI
CometChatApp.uiEvent("onLogout", () => {
  console.log("User logged out");
});
```

### Control where data is stored

Pick whether the widget should remember login info in the browser tab only (`SESSION`) or across visits (`LOCAL`). Update the placeholders, then drop this script right after the default widget embed.

```js lines highlight={5} theme={null}
const COMETCHAT_DATA = {
  appID: "<YOUR_APP_ID>",
  appRegion: "<YOUR_APP_REGION>",
  authKey: "<YOUR_AUTH_KEY>",
  storageMode: "SESSION", // or "LOCAL" (default)
};

const COMETCHAT_USER_UID = "UID"; // The person who should log in

const COMETCHAT_LAUNCH_OPTIONS = {
  targetElementID: "cometChatMount",
  isDocked: true,
  width: "700px",
  height: "500px",
};

window.addEventListener("DOMContentLoaded", () => {
  CometChatApp.init(COMETCHAT_DATA)
    .then(() => CometChatApp.login({ uid: COMETCHAT_USER_UID }))
    .then(() => CometChatApp.launch(COMETCHAT_LAUNCH_OPTIONS))
    .catch(console.error);
});

// Optional extras:
// COMETCHAT_LAUNCH_OPTIONS.variantID = "YOUR_VARIANT_ID";
// COMETCHAT_LAUNCH_OPTIONS.chatType = "user" | "group";
// COMETCHAT_LAUNCH_OPTIONS.defaultChatID = "uid_or_guid";
// COMETCHAT_LAUNCH_OPTIONS.dockedAlignment = "left" | "right";
```

### Change the widget language

The widget auto-detects the browser language, but you can force it to any supported locale. Run the helper once after the widget loads and swap in the language code you need.

```js theme={null}
CometChatApp.localize("en-US"); // Example: force English (United States)
```

**Popular codes**

| Language                 | Code    |
| ------------------------ | ------- |
| English (United States)  | `en-US` |
| English (United Kingdom) | `en-GB` |
| Dutch                    | `nl`    |
| French                   | `fr`    |
| German                   | `de`    |
| Hindi                    | `hi`    |
| Italian                  | `it`    |
| Japanese                 | `ja`    |
| Korean                   | `ko`    |
| Portuguese               | `pt`    |
| Russian                  | `ru`    |
| Spanish                  | `es`    |
| Turkish                  | `tr`    |
| Chinese (Simplified)     | `zh`    |
| Chinese (Traditional)    | `zh-TW` |
| Malay                    | `ms`    |
| Swedish                  | `sv`    |
| Lithuanian               | `lt`    |
| Hungarian                | `hu`    |

Need another locale? Use the same pattern with its code (for example `CometChatApp.localize("ko")` for Korean).

***

## Troubleshooting

* **Widget not appearing?**
  * Confirm the embed script loads (check **Network** tab for `chat-embed@1.x.x`)
  * Ensure the `<div id="cometChatMount"></div>` exists once per page and is not hidden by theme CSS
* **Only guest IDs show up?**
  * Customer accounts must be enabled, and you need to preview as a logged-in shopper—not inside the Theme Editor preview
  * Inspect `window.CURRENT_USER_ID` / `window.CURRENT_USER_NAME` in the console to confirm Shopify is populating them
* **Login or user-creation errors?**
  * Use an **App Auth Key** (not REST API key) so `CometChatApp.createOrUpdateUser` can run
  * Check the Users tab in your CometChat Dashboard to ensure the UID being generated does not violate UID rules

***

## Need Help?

Reach out to [CometChat Support](https://www.cometchat.com/contact) or visit our [docs site](https://www.cometchat.com/docs) for more examples.
