Skip to main content
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.
Remove the listener when you no longer need it:
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.
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.
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.

Search Capabilities

By default, search only matches message text. With Conversation & Advanced Search enabled, it also matches file names, mentions, and MIME types.
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.

Single Conversation

All Conversations

Excluding Blocked Users

Pass true as the last argument to any of the methods above:
CometChat.getUnreadMessageCountForUser(UID, true);
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