Skip to main content
FieldValue
Key ClassesCometChat.MessageListener, CometChat.MessagesRequestBuilder
Key MethodsaddMessageListener(), fetchPrevious(), fetchNext(), getUnreadMessageCount()
Listener EventsonTextMessageReceived, onMediaMessageReceived, onCustomMessageReceived
PrerequisitesSDK initialized, user logged in
Receiving messages with CometChat has two parts:
  1. Adding a real-time listener to receive messages while your app is running
  2. Fetching unread, or historical messages when your app starts up or the user scrolls back
The TypeScript and JavaScript APIs are identical — the only difference is type annotations (e.g., : string, : CometChat.BaseMessage[]). The Real-Time Messages section shows both for reference. The remaining sections use TypeScript only to keep things concise — just drop the type annotations for plain JavaScript.

Real-Time Messages

Register a MessageListener to receive incoming messages as they arrive. Each callback receives the specific message subclass — TextMessage, MediaMessage, or CustomMessage.
let listenerID: string = "UNIQUE_LISTENER_ID";

CometChat.addMessageListener(
  listenerID,
  new CometChat.MessageListener({
    onTextMessageReceived: (textMessage: CometChat.TextMessage) => {
      console.log("Text message received successfully", textMessage);
    },
    onMediaMessageReceived: (mediaMessage: CometChat.MediaMessage) => {
      console.log("Media message received successfully", mediaMessage);
    },
    onCustomMessageReceived: (customMessage: CometChat.CustomMessage) => {
      console.log("Custom message received successfully", customMessage);
    },
  })
);
ParameterDescription
listenerIDAn ID that uniquely identifies that listener. Use the same ID to remove it later.
Remove the listener when you no longer need it:
CometChat.removeMessageListener("UNIQUE_LISTENER_ID");
Always remove listeners when they’re no longer needed (e.g., on component unmount). Failing to do so can cause memory leaks and duplicate event handling.
As a sender, you will not receive your own message in a real-time event. However, if a user is logged in on multiple devices, they will receive the event on the other devices.

Unread Messages

Fetch unread messages by adding setUnread(true) to the builder. Use fetchPrevious() to retrieve them.
let UID: string = "UID";
let limit: number = 30;

let messagesRequest: CometChat.MessagesRequest =
  new CometChat.MessagesRequestBuilder()
    .setUID(UID)
    .setUnread(true)
    .setLimit(limit)
    .build();

messagesRequest.fetchPrevious().then(
  (messages: CometChat.BaseMessage[]) => {
    console.log("Message list fetched:", messages);
  },
  (error: CometChat.CometChatException) => {
    console.log("Message fetching failed with error:", error);
  }
);
Results are returned as BaseMessage objects, which may be instances of TextMessage, MediaMessage, CustomMessage, Action, or Call. Use the instanceof operator to check the type.

Message History

Fetch the full conversation history using fetchPrevious(). Call it repeatedly on the same request object to paginate — useful for implementing upward scrolling.
let UID: string = "UID";
let limit: number = 30;

let messagesRequest: CometChat.MessagesRequest =
  new CometChat.MessagesRequestBuilder()
    .setUID(UID)
    .setLimit(limit)
    .build();

messagesRequest.fetchPrevious().then(
  (messages: CometChat.BaseMessage[]) => {
    console.log("Message list fetched:", messages);
  },
  (error: CometChat.CometChatException) => {
    console.log("Message fetching failed with error:", error);
  }
);
The fetchPrevious() method returns an array of BaseMessage objects (which may be TextMessage, MediaMessage, or other subclasses).

Search Messages

Add setSearchKeyword() to the builder to filter messages by keyword.
let UID: string = "UID";
let limit: number = 30;
let searchKeyword: string = "Hello";

let messagesRequest: CometChat.MessagesRequest =
  new CometChat.MessagesRequestBuilder()
    .setUID(UID)
    .setLimit(limit)
    .setSearchKeyword(searchKeyword)
    .build();

messagesRequest.fetchPrevious().then(
  (messages: CometChat.BaseMessage[]) => {
    console.log("Message list fetched:", messages);
  },
  (error: CometChat.CometChatException) => {
    console.log("Message fetching failed with error:", error);
  }
);

Search Capabilities

By default, search only matches message text. With Conversation & Advanced Search enabled, it also matches file names, mentions, and MIME types.
FeatureBasic SearchAdvanced Search
Text search
File name search
Mentions search
MIME type search
Conversation & Advanced Search is available on Advanced and Custom plans. Enable it from the CometChat Dashboard under Chats → Settings → General Configuration.

Unread Message Count

CometChat provides several methods to get unread counts at different scopes. All return a Promise that resolves with an object mapping IDs to counts. Each method accepts an optional boolean parameter to exclude messages from blocked users.
MethodScopeReturns
getUnreadMessageCountForUser(UID)Single user conversation{ [UID]: count }
getUnreadMessageCountForGroup(GUID)Single group conversation{ [GUID]: count }
getUnreadMessageCountForAllUsers()All user conversations{ [UID]: count, ... }
getUnreadMessageCountForAllGroups()All group conversations{ [GUID]: count, ... }
getUnreadMessageCount()Everything{ users: { ... }, groups: { ... } }

Single Conversation

// One-on-one
let UID: string = "UID";
CometChat.getUnreadMessageCountForUser(UID).then(
  (count: Object) => console.log("Unread count:", count),
  (error: CometChat.CometChatException) => console.log("Error:", error)
);

// Group
let GUID: string = "GUID";
CometChat.getUnreadMessageCountForGroup(GUID).then(
  (count: Object) => console.log("Unread count:", count),
  (error: CometChat.CometChatException) => console.log("Error:", error)
);

All Conversations

// All users and groups combined
CometChat.getUnreadMessageCount().then(
  (count: Object) => console.log("Unread count:", count),
  (error: CometChat.CometChatException) => console.log("Error:", error)
);

// All user conversations only
CometChat.getUnreadMessageCountForAllUsers().then(
  (count: Object) => console.log("Unread count:", count),
  (error: CometChat.CometChatException) => console.log("Error:", error)
);

// All group conversations only
CometChat.getUnreadMessageCountForAllGroups().then(
  (count: Object) => console.log("Unread count:", count),
  (error: CometChat.CometChatException) => console.log("Error:", error)
);

Excluding Blocked Users

Pass true as the last argument to any of the methods above:
CometChat.getUnreadMessageCountForUser(UID, true);
CometChat.getUnreadMessageCountForGroup(GUID, true);
CometChat.getUnreadMessageCount(true);
CometChat.getUnreadMessageCountForAllUsers(true);
CometChat.getUnreadMessageCountForAllGroups(true);

Get Message Details

Use getMessageDetails() to fetch a specific message by its ID. Returns the full message object (TextMessage, MediaMessage, or CustomMessage).
let messageId: string = "MESSAGE_ID";

CometChat.getMessageDetails(messageId).then(
  (message: CometChat.BaseMessage) => {
    console.log("Message details:", message);
  },
  (error: CometChat.CometChatException) => {
    console.log("Error fetching message details:", error);
  }
);
ParameterTypeDescription
messageIdstringThe ID of the message to fetch
Returns a BaseMessage object (which may be a TextMessage, MediaMessage, or CustomMessage).

Next Steps

Delivery & Read Receipts

Track when messages are delivered and read by recipients

Typing Indicators

Show real-time typing status in conversations