Skip to main content
Quick Reference for AI Agents & Developers
// Core Entities
Useruid, name, avatar, status, metadata
Groupguid, name, type (public/password/private), membersCount
Messageid, sender, receiver, type (text/media/custom), category
ConversationconversationId, type (user/group), lastMessage, unreadCount

// Key Constants
CometChat.RECEIVER_TYPE.USER | GROUP
CometChat.MESSAGE_TYPE.TEXT | IMAGE | VIDEO | AUDIO | FILE
CometChat.GROUP_TYPE.PUBLIC | PASSWORD | PRIVATE
CometChat.GROUP_MEMBER_SCOPE.ADMIN | MODERATOR | PARTICIPANT

// Essential Listeners
MessageListeneronTextMessageReceived, onMediaMessageReceived, onTypingStarted
UserListeneronUserOnline, onUserOffline
GroupListeneronGroupMemberJoined, onGroupMemberLeft, onGroupMemberKicked
CallListeneronIncomingCallReceived, onOutgoingCallAccepted
ConnectionListeneronConnected, onDisconnected

// Security: Auth Key (dev only) vs Auth Token (production)
// Use REST API Key server-side only, never expose in client
Before diving into implementation, understanding these core concepts will help you build better chat experiences. This guide covers everything you need to know about how CometChat works.

How CometChat Works

CometChat provides the messaging infrastructure so you can focus on your app’s unique features.
ComponentWhat It DoesWhen to Use
SDKReal-time messaging from clientSending/receiving messages, presence, typing
REST APIServer-side operationsCreating users, generating auth tokens
DashboardConfiguration & monitoringSetup, analytics, testing
WebSocketReal-time event deliveryAutomatic (SDK manages this)
Key Principle: CometChat handles messaging infrastructure. You handle user management and business logic in your app.

CometChat Dashboard

The CometChat Dashboard is your control center:
1

Create Your App

Sign up and create a new app. Choose a region closest to your users.
2

Get Credentials

Navigate to API & Auth Keys to find your App ID, Region, and Auth Key.
3

Configure Features

Enable extensions, set up webhooks, and configure settings.
4

Test with Sample Users

Use the pre-created test users (cometchat-uid-1 to cometchat-uid-5) for development.
5

Monitor Usage

Track messages, users, and API calls in the Analytics section.
How many apps should I create?Create two apps: one for development and one for production. Use a single app across all platforms (web, iOS, Android) so users can communicate regardless of their device.

API Keys & Security

CometChat provides different keys for different purposes:
KeyAccess LevelWhere to UseSecurity
App IDIdentifies your appClient & ServerPublic (safe to expose)
Auth KeyCreate/login usersClient (dev only)⚠️ Development only
REST API KeyFull admin accessServer only🔒 Never expose
Auth TokenSingle user sessionClient✅ Production recommended
Security Rules:
  1. Never expose REST API Key in client code
  2. Use Auth Key only during development
  3. In production, generate Auth Tokens server-side

Users

A User represents anyone who can send or receive messages in your app.

User Lifecycle

User Identifier (UID)

Each user needs a unique identifier:
RuleValidInvalid
Alphanumericuser123, john_doe-
Underscoresuser_name-
Hyphensuser-456-
No spaces-user 123
No special chars-john@doe, user.name
Case-sensitiveUser1user1-
Best Practice: Use the same user ID from your database as the CometChat UID for easy mapping.

User Properties

// Creating a user with all properties
const user = new CometChat.User("user123");
user.setName("John Doe");
user.setAvatar("https://example.com/avatar.png");
user.setRole("premium");
user.setMetadata({
  department: "Engineering",
  location: "New York"
});
user.setTags(["developer", "team-alpha"]);
user.setStatusMessage("Available for chat");

// Create the user (requires Auth Key)
CometChat.createUser(user, authKey);
PropertyTypeDescriptionEditable
uidstringUnique identifierCreate only
namestringDisplay name
avatarstringProfile picture URL
rolestringRole for filtering/permissions
metadataobjectCustom JSON data
tagsarrayTags for categorization
statusMessagestringCustom status text
statusstringonline / offline❌ (system)
lastActiveAtnumberLast activity timestamp❌ (system)

User Roles

Roles help you segment users and control features:
// Filter users by role
const usersRequest = new CometChat.UsersRequestBuilder()
  .setRoles(["premium", "moderator"])
  .build();

// Subscribe to presence for specific roles only
const appSettings = new CometChat.AppSettingsBuilder()
  .subscribePresenceForRoles(["premium", "vip"])
  .setRegion(region)
  .build();
Example RoleUse Case
defaultRegular users
premiumPaid subscribers
moderatorContent moderators
adminApp administrators
supportCustomer support agents

Groups

A Group enables multiple users to communicate together.

Group Types

TypeVisibilityJoin MethodUse Case
PublicEveryoneOpen joinCommunity channels, public forums
PasswordEveryonePassword requiredSemi-private rooms, events
PrivateMembers onlyInvitation (auto-join)Team chats, support tickets
// Create different group types
const publicGroup = new CometChat.Group(
  "community",
  "Community Chat",
  CometChat.GROUP_TYPE.PUBLIC
);

const passwordGroup = new CometChat.Group(
  "event-123",
  "VIP Event",
  CometChat.GROUP_TYPE.PASSWORD,
  "secretPassword"
);

const privateGroup = new CometChat.Group(
  "team-alpha",
  "Team Alpha",
  CometChat.GROUP_TYPE.PRIVATE
);

Member Scopes (Permissions)

ScopeAssigned ToCapabilities
AdminGroup creator (default)Full control: delete group, manage all members, change settings
ModeratorPromoted by adminModerate: kick/ban participants, update group info
ParticipantAll other membersBasic: send/receive messages, join calls
// Add member with specific scope
const member = new CometChat.GroupMember(
  "user123",
  CometChat.GROUP_MEMBER_SCOPE.MODERATOR
);

// Change member scope
CometChat.updateGroupMemberScope(
  "group-guid",
  "user123",
  CometChat.GROUP_MEMBER_SCOPE.ADMIN
);

Group Properties

// Create group with all properties
const group = new CometChat.Group(
  "team-123",           // GUID
  "Engineering Team",   // Name
  CometChat.GROUP_TYPE.PRIVATE
);

group.setIcon("https://example.com/group-icon.png");
group.setDescription("Engineering team discussions");
group.setMetadata({ department: "Engineering", project: "Alpha" });
group.setTags(["engineering", "internal"]);

CometChat.createGroup(group);

Messages

Messages are the core of chat functionality. CometChat supports multiple message types and categories.

Message Categories & Types

CategoryDescriptionExamples
messageStandard messagesText, images, videos, files
customYour custom typesLocation, polls, payments
actionSystem eventsMember joined, message deleted
callCall eventsCall initiated, ended

Sending Different Message Types

const textMessage = new CometChat.TextMessage(
  "receiver-uid",           // Receiver UID or GUID
  "Hello, how are you?",    // Message text
  CometChat.RECEIVER_TYPE.USER  // USER or GROUP
);

// Optional: Add metadata
textMessage.setMetadata({ priority: "high" });

// Optional: Add tags
textMessage.setTags(["important"]);

CometChat.sendMessage(textMessage).then(
  (message) => console.log("Sent:", message),
  (error) => console.log("Error:", error)
);

Message Properties

PropertyMethodDescription
IDgetId()Unique message identifier
SendergetSender()User who sent the message
ReceivergetReceiver()User or Group receiving
TypegetType()text, image, video, etc.
CategorygetCategory()message, custom, action, call
Sent AtgetSentAt()Timestamp when sent
Delivered AtgetDeliveredAt()When delivered
Read AtgetReadAt()When read
Edited AtgetEditedAt()When edited (if edited)
Deleted AtgetDeletedAt()When deleted (if deleted)
MetadatagetMetadata()Custom data attached
TagsgetTags()Tags for filtering

Conversations

A Conversation represents a chat thread and is automatically created when messages are exchanged.

Conversation Types

TypeDescriptionCreated When
UserOne-on-one chatFirst message between two users
GroupGroup chatUser joins or messages a group

Conversation Properties

// Fetch conversations
const conversationsRequest = new CometChat.ConversationsRequestBuilder()
  .setLimit(30)
  .build();

conversationsRequest.fetchNext().then((conversations) => {
  conversations.forEach((conversation) => {
    // Conversation details
    console.log("ID:", conversation.getConversationId());
    console.log("Type:", conversation.getConversationType()); // "user" or "group"
    console.log("Unread:", conversation.getUnreadMessageCount());
    console.log("Updated:", conversation.getUpdatedAt());
    
    // Last message
    const lastMessage = conversation.getLastMessage();
    console.log("Last message:", lastMessage?.getText());
    
    // Conversation partner (user or group)
    const partner = conversation.getConversationWith();
    console.log("With:", partner.getName());
  });
});
PropertyMethodDescription
IDgetConversationId()Unique conversation ID
TypegetConversationType()user or group
Last MessagegetLastMessage()Most recent message
Unread CountgetUnreadMessageCount()Number of unread messages
Updated AtgetUpdatedAt()Last activity timestamp
Conversation WithgetConversationWith()User or Group object
TagsgetTags()Conversation tags

Building a Chat List

// Typical "Recent Chats" implementation
async function loadRecentChats() {
  const request = new CometChat.ConversationsRequestBuilder()
    .setLimit(30)
    .build();

  const conversations = await request.fetchNext();
  
  return conversations.map((conv) => ({
    id: conv.getConversationId(),
    name: conv.getConversationWith().getName(),
    avatar: conv.getConversationWith().getAvatar(),
    lastMessage: conv.getLastMessage()?.getText() || "No messages",
    unreadCount: conv.getUnreadMessageCount(),
    timestamp: conv.getUpdatedAt(),
    isGroup: conv.getConversationType() === "group"
  }));
}

Real-Time Events

CometChat uses WebSocket connections to deliver events instantly. You register listeners to handle these events.

Available Listeners

ListenerEventsUse Case
MessageListenerMessages, typing, receipts, reactionsChat UI updates
UserListenerOnline/offline statusPresence indicators
GroupListenerMember changes, scope changesGroup roster updates
CallListenerIncoming/outgoing callsCall handling
ConnectionListenerConnected/disconnectedNetwork status UI

Registering Listeners

const listenerID = "UNIQUE_MESSAGE_LISTENER";

CometChat.addMessageListener(
  listenerID,
  new CometChat.MessageListener({
    onTextMessageReceived: (message) => {
      console.log("Text received:", message.getText());
      // Update your chat UI
    },
    onMediaMessageReceived: (message) => {
      console.log("Media received:", message.getAttachment());
    },
    onTypingStarted: (typingIndicator) => {
      console.log(typingIndicator.getSender().getName(), "is typing...");
    },
    onTypingEnded: (typingIndicator) => {
      console.log(typingIndicator.getSender().getName(), "stopped typing");
    },
    onMessagesDelivered: (receipt) => {
      console.log("Message delivered:", receipt.getMessageId());
    },
    onMessagesRead: (receipt) => {
      console.log("Message read:", receipt.getMessageId());
    },
    onMessageEdited: (message) => {
      console.log("Message edited:", message.getId());
    },
    onMessageDeleted: (message) => {
      console.log("Message deleted:", message.getId());
    }
  })
);

// Remove when done (e.g., component unmount)
CometChat.removeMessageListener(listenerID);
Important Rules:
  1. Use unique listener IDs - duplicate IDs will overwrite previous listeners
  2. Remove listeners when components unmount to prevent memory leaks
  3. Register listeners after login - they won’t work before authentication

Integration Patterns

Pattern 1: User Registration Flow

Pattern 2: Existing User Login Flow

Pattern 3: Chat Screen Initialization

// Typical chat screen setup
async function initializeChatScreen(conversationId, conversationType) {
  // 1. Register message listener
  CometChat.addMessageListener(
    "CHAT_SCREEN_LISTENER",
    new CometChat.MessageListener({
      onTextMessageReceived: (message) => addMessageToUI(message),
      onMediaMessageReceived: (message) => addMessageToUI(message),
      onTypingStarted: (indicator) => showTypingIndicator(indicator),
      onTypingEnded: (indicator) => hideTypingIndicator(indicator),
      onMessagesRead: (receipt) => updateReadStatus(receipt)
    })
  );

  // 2. Fetch message history
  const messagesRequest = new CometChat.MessagesRequestBuilder()
    [conversationType === "user" ? "setUID" : "setGUID"](conversationId)
    .setLimit(30)
    .build();

  const messages = await messagesRequest.fetchPrevious();
  displayMessages(messages);

  // 3. Mark conversation as read
  if (messages.length > 0) {
    CometChat.markAsRead(messages[messages.length - 1]);
  }
}

// Cleanup when leaving chat screen
function cleanupChatScreen() {
  CometChat.removeMessageListener("CHAT_SCREEN_LISTENER");
}

Integration Checklist

StepYour AppCometChatWhen
User signs upSave to databaseCreate user (REST API)Registration
User logs inVerify credentialsGenerate auth token → SDK loginLogin
Open chat list-Fetch conversationsApp load
Open chat-Fetch messages, add listenersEnter chat
Send message-SDK handlesUser action
Receive message-Listener callbackReal-time
User logs outClear sessionCometChat.logout()Logout

Common Patterns & Best Practices

When to create CometChat users:
  • Create during user registration in your app
  • Use the same UID as your database user ID
// Your server-side code (Node.js example)
async function registerUser(email, password, name) {
  // 1. Create user in your database
  const user = await db.users.create({ email, password, name });
  
  // 2. Create user in CometChat
  await fetch(`https://api-${REGION}.cometchat.io/v3/users`, {
    method: "POST",
    headers: {
      "apiKey": REST_API_KEY,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      uid: user.id,  // Use same ID
      name: name
    })
  });
  
  return user;
}
// Track connection status
let isOnline = false;
const pendingMessages = [];

CometChat.addConnectionListener(
  "CONNECTION_HANDLER",
  new CometChat.ConnectionListener({
    onConnected: () => {
      isOnline = true;
      // Send any queued messages
      pendingMessages.forEach(msg => CometChat.sendMessage(msg));
      pendingMessages.length = 0;
    },
    onDisconnected: () => {
      isOnline = false;
    }
  })
);

// Queue messages when offline
function sendMessage(message) {
  if (isOnline) {
    return CometChat.sendMessage(message);
  } else {
    pendingMessages.push(message);
    return Promise.resolve(message); // Optimistic UI
  }
}
// React example with cleanup
useEffect(() => {
  const listenerID = `chat-${conversationId}`;
  
  CometChat.addMessageListener(
    listenerID,
    new CometChat.MessageListener({
      onTextMessageReceived: handleNewMessage
    })
  );

  // Cleanup on unmount or conversation change
  return () => {
    CometChat.removeMessageListener(listenerID);
  };
}, [conversationId]);
class MessagePaginator {
  constructor(uid) {
    this.request = new CometChat.MessagesRequestBuilder()
      .setUID(uid)
      .setLimit(30)
      .build();
    this.hasMore = true;
  }

  async loadMore() {
    if (!this.hasMore) return [];
    
    const messages = await this.request.fetchPrevious();
    this.hasMore = messages.length === 30;
    return messages;
  }
}

// Usage
const paginator = new MessagePaginator("user123");
const firstPage = await paginator.loadMore();
// On scroll up...
const secondPage = await paginator.loadMore();

Quick Reference

SDK Constants

// Receiver Types
CometChat.RECEIVER_TYPE.USER
CometChat.RECEIVER_TYPE.GROUP

// Message Types
CometChat.MESSAGE_TYPE.TEXT
CometChat.MESSAGE_TYPE.IMAGE
CometChat.MESSAGE_TYPE.VIDEO
CometChat.MESSAGE_TYPE.AUDIO
CometChat.MESSAGE_TYPE.FILE

// Group Types
CometChat.GROUP_TYPE.PUBLIC
CometChat.GROUP_TYPE.PASSWORD
CometChat.GROUP_TYPE.PRIVATE

// Member Scopes
CometChat.GROUP_MEMBER_SCOPE.ADMIN
CometChat.GROUP_MEMBER_SCOPE.MODERATOR
CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT

// Call Types
CometChat.CALL_TYPE.AUDIO
CometChat.CALL_TYPE.VIDEO

// User Status
CometChat.USER_STATUS.ONLINE
CometChat.USER_STATUS.OFFLINE

Common Methods Cheat Sheet

ActionMethod
InitializeCometChat.init(appID, appSettings)
LoginCometChat.login(uid, authKey) or CometChat.login(authToken)
LogoutCometChat.logout()
Get logged-in userCometChat.getLoggedinUser()
Send text messageCometChat.sendMessage(textMessage)
Send mediaCometChat.sendMediaMessage(mediaMessage)
Fetch messagesmessagesRequest.fetchPrevious()
Fetch conversationsconversationsRequest.fetchNext()
Fetch usersusersRequest.fetchNext()
Fetch groupsgroupsRequest.fetchNext()
Join groupCometChat.joinGroup(guid, type, password?)
Leave groupCometChat.leaveGroup(guid)
Mark as readCometChat.markAsRead(message)
Start typingCometChat.startTyping(typingIndicator)
End typingCometChat.endTyping(typingIndicator)

Glossary

Quick reference for terms used throughout the CometChat JavaScript SDK documentation.
TermDefinition
UIDUser Identifier. A unique string you assign to each user. Alphanumeric, underscores, and hyphens only.
GUIDGroup Unique Identifier. A unique string you assign to each group. Same character rules as UID.
App IDYour application’s unique identifier from the CometChat Dashboard. Safe to include in client code.
Auth KeyA key for client-side login during development. Never use in production — use Auth Tokens instead.
Auth TokenA short-lived token generated server-side via REST API. The secure way to authenticate users in production.
REST API KeyA server-only key with full admin access. Never expose in client-side code.
RegionThe server region your app runs on (us, eu, or in). Set during app creation.
Receiver TypeWhether a message target is a USER or GROUP. Set via CometChat.RECEIVER_TYPE.
Message CategoryHigh-level classification: message, custom, action, or call.
Message TypeSpecific type within a category: text, image, video, audio, file, or your custom types.
ScopeA group member’s permission level: admin, moderator, or participant.
ListenerA callback object registered with the SDK to receive real-time events (messages, presence, group changes, calls).
ConversationAn auto-created thread between a user pair or within a group. Tracks last message and unread count.
MetadataArbitrary JSON data you can attach to users, groups, or messages for custom use cases.
TagsString labels you can attach to users, groups, messages, or conversations for filtering and categorization.

Next Steps