Skip to main content
Add the CometChat Widget by pasting one small code snippet. It drops in like any other embed—copy the code, paste it into your site’s Code Injection, then tell the widget how people should sign in. Choose the sign-in option that matches your site:

Steps to Add Custom Code in Squarespace (via Code Injection)

  1. Log in to Squarespace and open your website dashboard.
  2. In the left sidebar, click Website (top-left) and select the site.
  3. Scroll to Marketing Tools and click Custom Code.
  4. Click Code Injection.
  5. You’ll see Header and Footer. Paste your chosen integration snippet into Footer.
  6. Click Save.
  7. Refresh your site and open a page to confirm chat loads.

1. Anonymous Chat (Guest Mode)

Use this when:
  • You want visitors to chat without creating accounts.
  • You don’t have a member area or user authentication.
  • You want quick, friction-free chat access.
<div id="cometChatMount"></div>
<script defer src="https://cdn.jsdelivr.net/npm/@cometchat/chat-embed@1.x.x/dist/main.js"></script>

<script>
  const COMETCHAT_WIDGET_CONFIG = {
    appID: "YOUR_APP_ID",
    region: "YOUR_APP_REGION",
    mode: "guest",
    authKey: "YOUR_AUTH_KEY",

    user: {
      name: "Guest User",
      avatar: "",
      link: ""
    },

    mount: "#cometChatMount",
    width: "450px",
    height: "80vh",
    isDocked: true,
  };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
      CometChatApp.CometChatAuth.start(COMETCHAT_WIDGET_CONFIG);
    });
  } else {
    CometChatApp.CometChatAuth.start(COMETCHAT_WIDGET_CONFIG);
  }
</script>
Update these values:
  • appID, region, authKey: Copy from Dashboard.
  • user.name, user.avatar, user.link: Optional guest display info.
  • width, height, isDocked: Widget dimensions (isDocked = true = floating icon; false = embedded).

2. Create + Log In User On The Fly (Squarespace Members)

Use this when:
  • You have Squarespace Member Areas enabled.
  • You want members to automatically get CometChat accounts.
  • You want to support both members and guest visitors.
<div id="cometChatMount"></div>
<script defer src="https://cdn.jsdelivr.net/npm/@cometchat/chat-embed@1.x.x/dist/main.js"></script>

<script>
  const COMETCHAT_CONFIG = {
    appID: "YOUR_APP_ID",
    region: "YOUR_APP_REGION",
    authKey: "YOUR_AUTH_KEY",
  };

  const WIDGET_SETTINGS = {
    targetElementID: "cometChatMount",
    width: "450px",
    height: "80vh",
    isDocked: true,
  };

  function getSquarespaceMember() {
    const name = "SiteUserInfo=";
    const decodedCookie = decodeURIComponent(document.cookie);
    const ca = decodedCookie.split(';');
    
    for (let i = 0; i < ca.length; i++) {
      let c = ca[i].trim();
      if (c.indexOf(name) === 0) {
        try {
          const userData = JSON.parse(c.substring(name.length, c.length));
          if (userData.authenticated) {
            return {
              uid: userData.siteUserId,
              name: userData.firstName || "Member",
              isMember: true
            };
          }
        } catch (e) {
          console.error("Failed to parse Squarespace user cookie", e);
        }
      }
    }
    return null;
  }

  async function initializeCometChat() {
    try {
      const member = getSquarespaceMember();
      let user;

      if (member) {
        user = member;
      } else {
        let guestId = localStorage.getItem('cometchat_guest_id') || 
                      ('guest_' + Math.random().toString(36).substr(2, 9));
        localStorage.setItem('cometchat_guest_id', guestId);
        user = { uid: guestId, name: "Guest User", isMember: false };
      }

      await CometChatApp.init(COMETCHAT_CONFIG);
      const loggedInUser = await CometChatApp.CometChat.getLoggedinUser();

      if (!loggedInUser || loggedInUser.uid !== user.uid) {
        if (loggedInUser) await CometChatApp.logout();

        const ccUser = new CometChatApp.CometChat.User(user.uid);
        ccUser.setName(user.name);
        
        try {
          await CometChatApp.createOrUpdateUser(ccUser);
        } catch (e) {
          console.warn("User creation skipped:", e.message);
        }

        await CometChatApp.login({ 
          uid: user.uid, 
          authKey: COMETCHAT_CONFIG.authKey 
        });
      }

      CometChatApp.launch(WIDGET_SETTINGS);
    } catch (error) {
      console.error("CometChat Integration Error:", error);
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeCometChat);
  } else {
    initializeCometChat();
  }
</script>
How it works:
  • Detects Squarespace members via the SiteUserInfo cookie.
  • Creates CometChat users on-the-fly when members first visit; falls back to guest for others.
  • Persists guest IDs in localStorage to keep a consistent identity.

3. Backend-Created User (Auth Token Login)

Use this when: people sign in through your backend and you generate their CometChat auth token server-side. This keeps your Auth Key off the page. Server-side flow (auth token login):
  1. Authenticate the user in your app.
  2. If it’s their first time, call Create User (https://www.cometchat.com/docs/rest-api/users/create) — you can also request an auth token in that call.
  3. For returning users, call Create Auth Token (https://www.cometchat.com/docs/rest-api/auth-tokens/create) to issue a fresh token.
  4. Send the token to the browser and place it in the widget config below.
  5. The same token works for the CometChat Widget, UI Kit, or SDK.
Full walkthrough: How to properly log in and create users in CometChat. Use this when:
  • You need maximum security (no authKey exposed in the frontend).
  • You have a custom backend or serverless functions.
  • You want full control over user creation and authentication.
<div id="cometChatMount"></div>
<script defer src="https://cdn.jsdelivr.net/npm/@cometchat/chat-embed@1.x.x/dist/main.js"></script>

<script>
  const COMETCHAT_WIDGET_CONFIG = {
    appID: "YOUR_APP_ID",
    region: "YOUR_APP_REGION",
    mode: "authToken",
    authToken: "USER_AUTH_TOKEN",

    mount: "#cometChatMount",
    width: "450px",
    height: "80vh",
    isDocked: true,
  };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
      CometChatApp.CometChatAuth.start(COMETCHAT_WIDGET_CONFIG);
    });
  } else {
    CometChatApp.CometChatAuth.start(COMETCHAT_WIDGET_CONFIG);
  }
</script>
Update these values:
  • appID, region, authKey | Copy from Dashboard.
  • authToken | Generated by your backend and passed to this page.
  • width, height, isDocked | Adjust widget dimensions/placement.

Troubleshooting

  • Widget not appearing? Verify App ID, Region & Auth Key (or auth token), and check browser console for CSP/ad-blocker errors.
  • Login fails? For UID mode, ensure the uid exists or is created on first visit; for auth token mode, make sure the token matches the logged-in user.
  • Styling issues? Add custom CSS in Design → Custom CSS to override defaults.
  • Page-specific placement? Use a page-level Code Block instead of the global Footer if you only want it on one page.

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.
// 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.
// 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.
// 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.
// 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.
// 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.
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.
CometChatApp.localize("en-US"); // Example: force English (United States)
Popular codes
LanguageCode
English (United States)en-US
English (United Kingdom)en-GB
Dutchnl
Frenchfr
Germande
Hindihi
Italianit
Japaneseja
Koreanko
Portuguesept
Russianru
Spanishes
Turkishtr
Chinese (Simplified)zh
Chinese (Traditional)zh-TW
Malayms
Swedishsv
Lithuanianlt
Hungarianhu
Need another locale? Use the same pattern with its code (for example CometChatApp.localize("ko") for Korean).

Need Help?

If you have questions or run into issues, reach out to CometChat Support.