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 listener to receive real-time messages when your app is running
  2. Calling a method to retrieve missed messages when your app was not running

Real-Time Messages

Register the MessageListener to receive incoming messages in real-time using addMessageListener().
Always remove listeners when they’re no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling.
let listenerID = "UNIQUE_LISTENER_ID";

CometChat.addMessageListener(
  listenerID,
  new CometChat.MessageListener({
    onTextMessageReceived: (textMessage) => {
      console.log("Text message received successfully", textMessage);
    },
    onMediaMessageReceived: (mediaMessage) => {
      console.log("Media message received successfully", mediaMessage);
    },
    onCustomMessageReceived: (customMessage) => {
      console.log("Custom message received successfully", customMessage);
    },
  })
);
ParameterDescription
listenerIDAn ID that uniquely identifies that listener
Remove the listener when you no longer need to receive messages:
let listenerID = "UNIQUE_LISTENER_ID";

CometChat.removeMessageListener(listenerID);
As a sender, you will not receive your own message in a real-time message event. However, if a user is logged-in using multiple devices, they will receive an event for their own message in other devices.
Each listener callback receives the specific message subclass — TextMessage, MediaMessage, or CustomMessage — depending on the message type. Access the data using getter methods:
FieldGetterReturn TypeDescription
idgetId()numberUnique message ID
sendergetSender()UserThe user who sent the message
receiverIdgetReceiverId()stringUID or GUID of the receiver
typegetType()stringMessage type (text, image, custom, etc.)
sentAtgetSentAt()numberTimestamp when the message was sent
textgetText()stringText content (TextMessage only)

Missed Messages

Fetch messages that were sent while your app was offline using MessagesRequestBuilder with setMessageId() and fetchNext(). Use getLastDeliveredMessageId() to get the ID of the last delivered message, then fetch all messages after that point. Call fetchNext() repeatedly on the same object to paginate through all missed messages.

Fetch Missed Messages of a particular one-on-one conversation

let UID = "UID";
let limit = 30;
let latestId = await CometChat.getLastDeliveredMessageId();

let messagesRequest = new CometChat.MessagesRequestBuilder()
  .setUID(UID)
  .setMessageId(latestId)
  .setLimit(limit)
  .build();

messagesRequest.fetchNext().then(
  (messages) => {
    console.log("Message list fetched:", messages);
  },
  (error) => {
    console.log("Message fetching failed with error:", error);
  }
);

Fetch Missed Messages of a particular group conversation

let GUID = "GUID";
let limit = 30;
let latestId = await CometChat.getLastDeliveredMessageId();

let messagesRequest = new CometChat.MessagesRequestBuilder()
  .setGUID(GUID)
  .setMessageId(latestId)
  .setLimit(limit)
  .build();

messagesRequest.fetchNext().then(
  (messages) => {
    console.log("Message list fetched:", messages);
  },
  (error) => {
    console.log("Message fetching failed with error:", error);
  }
);
The fetchNext() method returns an array of BaseMessage objects (which may be TextMessage, MediaMessage, or other subclasses). Access the data using getter methods:
FieldGetterReturn TypeDescription
idgetId()numberUnique message ID
sendergetSender()UserThe user who sent the message
typegetType()stringMessage type (text, image, custom, etc.)
sentAtgetSentAt()numberTimestamp when the message was sent
conversationIdgetConversationId()stringID of the conversation the message belongs to

Unread Messages

Fetch unread messages by setting setUnread(true) on the builder.

Fetch Unread Messages of a particular one-on-one conversation

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

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

Fetch Unread Messages of a particular group conversation

let GUID = "GUID";
let limit = 30;
let messagesRequest = new CometChat.MessagesRequestBuilder()
  .setGUID(GUID)
  .setUnread(true)
  .setLimit(limit)
  .build();

messagesRequest.fetchPrevious().then(
  (messages) => {
    console.log("Message list fetched:", messages);
  },
  (error) => {
    console.log("Message fetching failed with error:", error);
  }
);
The list of messages received is in the form of BaseMessage objects. A BaseMessage can either be an object of the TextMessage, MediaMessage, CustomMessage, Action or Call class. You can use the instanceof operator to check the type of object.

Message History

Fetch the complete conversation history using MessagesRequestBuilder with fetchPrevious(). Call fetchPrevious() repeatedly on the same object to paginate through the entire conversation — useful for implementing upward scrolling.

Fetch Message History of a particular one-on-one conversation

Set the UID using setUID() to fetch the conversation with a specific user.
let UID = "UID";
let limit = 30;
let messagesRequest = new CometChat.MessagesRequestBuilder()
  .setUID(UID)
  .setLimit(limit)
  .build();

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

Fetch Message History of a particular group conversation

Set the GUID using setGUID() to fetch messages from a group you’ve joined.
let GUID = "GUID";
let limit = 30;
let messagesRequest = new CometChat.MessagesRequestBuilder()
  .setGUID(GUID)
  .setLimit(limit)
  .build();

messagesRequest.fetchPrevious().then(
  (messages) => {
    console.log("Message list fetched:", messages);
  },
  (error) => {
    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). Access the data using getter methods:
FieldGetterReturn TypeDescription
idgetId()numberUnique message ID
sendergetSender()UserThe user who sent the message
typegetType()stringMessage type (text, image, custom, etc.)
sentAtgetSentAt()numberTimestamp when the message was sent
conversationIdgetConversationId()stringID of the conversation the message belongs to

Search Messages

Use setSearchKeyword() to search for messages matching a keyword.
By default, the searchKey is searched only in message text. However, if you enable Conversation & Advanced Search, the searchKey will be searched in message text, file name, mentions & mime type of the file.The Conversation & Advanced Search is only available in Advanced & Custom plans. If you’re already on one of these plans, please enable the Conversation & Advanced Search from CometChat Dashboard (Open your app, navigate to Chats -> Settings -> General Configuration)
FeatureBasic SearchAdvance Search
Text search
File name search
Mentions search
Mime type search

Search Messages in a particular one-on-one conversation

let UID = "UID";
let limit = 30;
let searchKeyword = "Hello";
let messagesRequest = new CometChat.MessagesRequestBuilder()
  .setUID(UID)
  .setLimit(limit)
  .setSearchKeyword(searchKeyword)
  .build();

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

Search Messages in a particular group conversation

let GUID = "GUID";
let limit = 30;
let searchKeyword = "Hello";
let messagesRequest = new CometChat.MessagesRequestBuilder()
  .setGUID(GUID)
  .setLimit(limit)
  .setSearchKeyword(searchKeyword)
  .build();

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

Unread Message Count

Get the number of unread messages for users, groups, or all conversations.

Fetch Unread Message Count of a particular one-on-one conversation

Use getUnreadMessageCountForUser() to get the unread count for a specific user.
CometChat.getUnreadMessageCountForUser(UID);
To ignore messages from blocked users, set the boolean parameter to true:
CometChat.getUnreadMessageCountForUser(UID, hideMessagesFromBlockedUsers);
let UID = "UID";

CometChat.getUnreadMessageCountForUser(UID).then(
  (unreadMessageCountObject) => {
    console.log("Unread message count fetched", unreadMessageCountObject);
  },
  (error) => {
    console.log("Error in getting unread message count", error);
  }
);
Returns an object with the UID as key and unread message count as value.

Fetch Unread Message Count of a particular group conversation

Use getUnreadMessageCountForGroup() to get the unread count for a specific group.
CometChat.getUnreadMessageCountForGroup(GUID);
To ignore messages from blocked users, set the boolean parameter to true:
CometChat.getUnreadMessageCountForGroup(GUID, hideMessagesFromBlockedUsers);
let GUID = "GUID";

CometChat.getUnreadMessageCountForGroup(GUID).then(
  (unreadMessageCountObject) => {
    console.log("Unread message count fetched", unreadMessageCountObject);
  },
  (error) => {
    console.log("Error in getting unread message count", error);
  }
);
Returns an object with the GUID as key and unread message count as value.

Fetch Unread Message Count of all one-on-one & group conversations

Use getUnreadMessageCount() to get unread counts for all users and groups combined.
CometChat.getUnreadMessageCount();
To ignore messages from blocked users, set the boolean parameter to true:
CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers);
CometChat.getUnreadMessageCount().then(
  (unreadMessageCountObject) => {
    console.log("Unread message count fetched", unreadMessageCountObject);
  },
  (error) => {
    console.log("Error in getting unread message count", error);
  }
);
Returns an object with two keys:
  • users — Object with UIDs as keys and unread counts as values
  • groups — Object with GUIDs as keys and unread counts as values

Fetch Unread Message Count of all one-on-one conversations

Use getUnreadMessageCountForAllUsers() to get unread counts for all user conversations.
CometChat.getUnreadMessageCountForAllUsers();
To ignore messages from blocked users, set the boolean parameter to true:
CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers);
CometChat.getUnreadMessageCountForAllUsers().then(
  (unreadMessageCountObject) => {
    console.log("Unread message count fetched", unreadMessageCountObject);
  },
  (error) => {
    console.log("Error in getting unread message count", error);
  }
);
Returns an object with UIDs as keys and unread counts as values.

Fetch Unread Message Count of all group conversations

Use getUnreadMessageCountForAllGroups() to get unread counts for all group conversations.
CometChat.getUnreadMessageCountForAllGroups();
To ignore messages from blocked users, set the boolean parameter to true:
CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers);
CometChat.getUnreadMessageCountForAllGroups().then(
  (unreadMessageCountObject) => {
    console.log("Unread message count fetched", unreadMessageCountObject);
  },
  (error) => {
    console.log("Error in getting unread message count", error);
  }
);
Returns an object with GUIDs as keys and unread counts as values.

Next Steps

Delivery & Read Receipts

Track when messages are delivered and read by recipients

Typing Indicators

Show real-time typing status in conversations