> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-feature-react-native-sdk-quotedmessage-a.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 APIs

Once the widget is loaded, interact with it via the global `CometChatApp` object:

### Chat and Call Methods

```js theme={null}
// Chat with a particular user
CometChatApp.chatWithUser("UID");

// Chat with a particular group
CometChatApp.chatWithGroup("GUID");

// Initiate calls with a particular user
CometChatApp.callUser("UID");

// Initiate calls with a particular group
CometChatApp.callGroup("GUID");

// Show or hide action messages in group chats
CometChatApp.showGroupActionMessages(true);

// Show or hide unread message count bubble on docked layout
CometChatApp.showDockedUnreadCount(true);
```

### UI Event Listeners

```js theme={null}
// Message received listener
CometChatApp.uiEvent("onMessageReceived", (msg) => {
  console.log("New message received:", msg);
});

// Chat opened listener (for docked mode)
CometChatApp.uiEvent("onOpenChat", (args) => {
  console.log("Chat opened", args);
});

// Chat closed listener (for docked mode)
CometChatApp.uiEvent("onCloseChat", (args) => {
  console.log("Chat closed", args);
});

// Active chat change listener
CometChatApp.uiEvent("onActiveChatChanged", (args) => {
  console.log("onActiveChatChanged", args);
});
```

### User and Group Management

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

CometChatApp.createOrUpdateUser(user).then((createdUser) => {
  console.log("User created/updated", createdUser);
});

// Create or update a group on-the-fly
const group = new CometChatApp.CometChat.Group("GUID", "GROUP_NAME", "public");
CometChatApp.createOrUpdateGroup(group).then((createdGroup) => {
  console.log("Group created/updated", createdGroup);
});
```

### Authentication Methods

```js theme={null}
// Login with authToken
CometChatApp.login({ authToken: "your-auth-token" }); // More secure

// Login with UID
CometChatApp.login({ uid: "your-uid" });  // Less secure

// User logout
CometChatApp.logout();

// Logout listener
CometChatApp.uiEvent("onLogout", (args) => {
  console.log("onLogout", args);
});
```

### Storage Methods

```
const COMETCHAT_DATA = {
    appID:    "<YOUR_APP_ID>",
    appRegion: "<YOUR_APP_REGION>",
    authKey:   "<YOUR_AUTH_KEY>",
    storageMode:"SESSION" // "SESSION" || "LOCAL", defaults to "LOCAL"
};

const COMETCHAT_USER_UID = "UID"; // Replace with your actual user UID

const COMETCHAT_LAUNCH_OPTIONS = {
    targetElementID: "cometChatMount",   // Element ID to mount the widget
    isDocked:        true,               // true = floating bubble, false = embedded
    width:           "700px",            // Widget width
    height:          "500px",            // Widget height

    // Optional advanced settings:
    // variantID:        "YOUR_VARIANT_ID",    // Variant configuration ID
    // chatType:         "user",               // "user" or "group"
    // defaultChatID:    "uid_or_guid",        // UID or GUID to open chat by default
    // dockedAlignment:  "right",              // For docked mode: "left" or "right"
};

window.addEventListener("DOMContentLoaded", () => {
    CometChatApp.init(COMETCHAT_DATA)
      .then(() => {
        console.log("[CometChat] Initialized successfully");
        return CometChatApp.login({ uid: COMETCHAT_USER_UID });
      })
      .then(user => {
        console.log("[CometChat] Logged in as:", user);
        return CometChatApp.launch(COMETCHAT_LAUNCH_OPTIONS);
      })
      .then(() => {
        console.log("[CometChat] Chat launched!");
      })
      .catch(error => {
        console.error("[CometChat] Error:", error);
      });
  });
```

### Localization

With language localization, our Chat Widget adapts to the language of a specific country or region. Chat Widget allows you to detect the language of your users based on their browser settings and set the language of the widget accordingly.

You can also set the language manually using the `CometChatApp.localize` method.
The CometChat App supports localization for multiple languages, allowing you to provide a tailored experience for users across different regions.

You can find the list of supported languages and their corresponding language codes below:

| 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                  | `zh`    |
| Chinese (Traditional)    | `zh-TW` |
| Malay                    | `ms`    |
| Swedish                  | `sv`    |
| Lithuanian               | `lt`    |
| Hungarian                | `hu`    |

<Tabs>
  <Tab title="JavaScript">
    ```javascript theme={null}
    CometChatApp.localize(LANGUAGE_CODE);

    Eg. CometChatApp.localize('en-US');
    ```
  </Tab>
</Tabs>

It takes the following parameters:

| Parameter      | Description                                       | Type     |
| -------------- | ------------------------------------------------- | -------- |
| LANGUAGE\_CODE | The language code the texts to be translated into | Required |

***

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