Skip to main content
Quick Reference for AI Agents & Developers
Package: @cometchat/chat-sdk-javascript
Init: CometChat.init(appID, appSettings)
Login: CometChat.login(uid, authKey) or CometChat.login(authToken)
Send: CometChat.sendMessage(textMessage)
Receive: CometChat.addMessageListener(id, listener)
Logout: CometChat.logout()
Build powerful chat experiences in your web applications using CometChat’s JavaScript SDK. Whether you’re building with React, Angular, Vue, or vanilla JavaScript, this SDK provides the foundation for real-time messaging, voice, and video calling.
Choose Your Integration PathCometChat offers multiple ways to add chat to your application:
ApproachBest ForEffort
Widget BuilderQuick embed, minimal codingNo Code
UI Kit BuilderVisual customization with code exportLow Code
UI KitsPre-built components, full controlCode
SDK (this guide)Complete flexibility, custom UICode
REST APIServer-side integrationCode

Quick Start

Get up and running in 4 steps:
1

Get Your Credentials

Sign up for CometChat and create a new app. Note your App ID, Region, and Auth Key from the API & Auth Keys section.
2

Install the SDK

npm install @cometchat/chat-sdk-javascript
3

Initialize CometChat

import { CometChat } from "@cometchat/chat-sdk-javascript";

const appID = "YOUR_APP_ID";
const region = "YOUR_REGION";

const appSetting = new CometChat.AppSettingsBuilder()
  .subscribePresenceForAllUsers()
  .setRegion(region)
  .build();

CometChat.init(appID, appSetting).then(
  () => console.log("CometChat initialized successfully"),
  (error) => console.log("Initialization failed:", error)
);
CometChat.init() must be called before any other SDK method. Call it once at app startup — calling login(), sendMessage(), or registering listeners before init() will fail.
4

Login a User

const UID = "cometchat-uid-1";
const authKey = "YOUR_AUTH_KEY";

CometChat.login(UID, authKey).then(
  (user) => console.log("Login successful:", user),
  (error) => console.log("Login failed:", error)
);
We provide 5 test users: cometchat-uid-1 through cometchat-uid-5
Using Next.js, Nuxt, or another SSR framework? CometChat requires browser APIs and won’t work during server-side rendering. Use dynamic imports and client-only directives. See the Framework Integration section for complete setup guides for React, Next.js, Vue, Nuxt, and Angular.

What’s Next?


Core Features

Essential messaging capabilities built into the SDK:
FeatureDescriptionLearn More
Instant MessagingReal-time one-on-one and group chatSend Message
Media SharingShare images, videos, documents, and filesMedia Messages
Read ReceiptsKnow when messages are delivered and readDelivery & Read Receipts
Mark as UnreadMark messages as unread to revisit laterMark as Unread
Typing IndicatorsShow when users are typingTyping Indicators
User PresenceReal-time online/offline statusUser Presence
ReactionsReact to messages with emojisReactions
Mentions@mention users in conversationsMentions
Threaded ConversationsCreate message threads for organized discussionsThreaded Messages
Quoted RepliesReply to specific messages with contextQuoted Messages
Group ChatsCreate and manage group conversationsGroups
Report MessageAllow users to report inappropriate contentFlag Message
Conversation & Advanced SearchSearch messages by text, file name, mentions, or mime typeSearch Messages

Extensions

Enhance your chat with these optional features. Enable them from the CometChat Dashboard under Extensions.
ExtensionDescription
Message ShortcutsQuick shortcuts for common messages
AvatarsAuto-generated avatars for users
Link PreviewRich previews for shared URLs
Rich Media PreviewEnhanced previews for media content
Thumbnail GenerationAuto-generate thumbnails for images and videos
Pin MessagePin important messages in conversations
Save MessagesSave messages for later reference
TinyURLShorten long URLs automatically
BitlyURL shortening via Bitly integration
Voice TranscriptionTranscribe voice messages to text
ExtensionDescription
GiphySend animated GIFs
TenorAlternative GIF integration
Message TranslationTranslate messages in real-time
PollsCreate polls for group decisions
RemindersSet reminders for messages
StickersSend stickers in conversations
Stipop StickersPremium sticker packs via Stipop
EmojisEnhanced emoji support
ExtensionDescription
Collaborative DocumentCreate and share documents in real-time
Collaborative WhiteboardShared whiteboard for visual collaboration
ExtensionDescription
Disappearing MessagesMessages that auto-delete after a set time
End-to-End EncryptionSecure message encryption
ExtensionDescription
ChatwootConnect with Chatwoot for support workflows
IntercomIntegrate with Intercom for customer messaging
FeatureDescription
Conversation StarterAI-suggested conversation starters
Smart RepliesAI-generated reply suggestions
Conversation SummaryAI-generated summaries of conversations
Learn more about AI User Copilot →

Voice & Video Calling

Add real-time calling capabilities to your app: Explore all Calling features →

AI Features

Leverage AI to enhance your chat experience:

Framework Guides

Sample Apps

Explore complete implementations with UI:

Need Pre-Built UI?

If you prefer ready-to-use components instead of building from scratch:

Complete Working Example

Here’s a production-ready example that initializes CometChat, logs in, sends a message, and listens for responses:
import { CometChat } from "@cometchat/chat-sdk-javascript";

// Configuration
const APP_ID = "YOUR_APP_ID";
const REGION = "YOUR_REGION"; // "us", "eu", or "in"
const AUTH_KEY = "YOUR_AUTH_KEY";

class ChatService {
  static instance = null;
  
  static getInstance() {
    if (!ChatService.instance) {
      ChatService.instance = new ChatService();
    }
    return ChatService.instance;
  }

  async initialize() {
    const appSettings = new CometChat.AppSettingsBuilder()
      .subscribePresenceForAllUsers()
      .setRegion(REGION)
      .autoEstablishSocketConnection(true)
      .build();

    try {
      await CometChat.init(APP_ID, appSettings);
      console.log("✓ CometChat initialized");
      return true;
    } catch (error) {
      console.error("✗ Init failed:", error);
      return false;
    }
  }

  async login(uid) {
    try {
      // Check if already logged in
      let user = await CometChat.getLoggedinUser();
      if (user) {
        console.log("✓ Already logged in:", user.getName());
        return user;
      }

      // Login
      user = await CometChat.login(uid, AUTH_KEY);
      console.log("✓ Logged in:", user.getName());
      return user;
    } catch (error) {
      console.error("✗ Login failed:", error);
      throw error;
    }
  }

  async sendMessage(receiverUID, text) {
    const message = new CometChat.TextMessage(
      receiverUID,
      text,
      CometChat.RECEIVER_TYPE.USER
    );

    try {
      const sent = await CometChat.sendMessage(message);
      console.log("✓ Message sent:", sent.getId());
      return sent;
    } catch (error) {
      console.error("✗ Send failed:", error);
      throw error;
    }
  }

  startListening(onMessage) {
    const listenerID = "MAIN_LISTENER";
    
    CometChat.addMessageListener(
      listenerID,
      new CometChat.MessageListener({
        onTextMessageReceived: (message) => {
          console.log("← Received:", message.getText());
          onMessage?.(message);
        },
        onMediaMessageReceived: (message) => {
          console.log("← Media received:", message.getAttachment());
          onMessage?.(message);
        }
      })
    );

    return () => CometChat.removeMessageListener(listenerID);
  }

  async logout() {
    try {
      await CometChat.logout();
      console.log("✓ Logged out");
    } catch (error) {
      console.error("✗ Logout failed:", error);
    }
  }
}

// Usage
const chat = ChatService.getInstance();
await chat.initialize();
await chat.login("cometchat-uid-1");
chat.startListening((msg) => console.log("New message:", msg));
await chat.sendMessage("cometchat-uid-2", "Hello from the SDK!");

Common Errors & Solutions

Cause: The App ID doesn’t match any app in your CometChat account.Solution:
  1. Go to CometChat Dashboard
  2. Select your app → API & Auth Keys
  3. Copy the exact App ID (case-sensitive)
  4. Ensure no extra spaces when pasting
Cause: Using wrong key type or incorrect key.Solution:
  • Use Auth Key (not REST API Key) for client-side login
  • Auth Key is for development only; use Auth Tokens in production
  • Copy directly from Dashboard → API & Auth Keys
Cause: Trying to login with a UID that hasn’t been created.Solution:
  • Use test users: cometchat-uid-1 through cometchat-uid-5
  • Or create users via REST API before login
  • Check for typos in the UID
Cause: Calling SDK methods before successful login.Solution:
// Always check login status first
const user = await CometChat.getLoggedinUser();
if (!user) {
  await CometChat.login(uid, authKey);
}
// Now safe to use other methods
Cause: Message listener not registered or registered before login.Solution:
  1. Register listeners AFTER successful login
  2. Use unique listener IDs
  3. Check WebSocket connection: CometChat.getConnectionStatus()
  4. Ensure autoEstablishSocketConnection(true) in app settings
Cause: Browser security blocking requests.Solution:
  • CometChat handles CORS automatically
  • If using a proxy, ensure it forwards headers correctly
  • Check browser console for specific blocked URLs

SDK Method Reference

Quick lookup for common operations:
OperationMethodReturns
InitializeCometChat.init(appID, settings)Promise<boolean>
Login (Auth Key)CometChat.login(uid, authKey)Promise<User>
Login (Auth Token)CometChat.login(authToken)Promise<User>
LogoutCometChat.logout()Promise<void>
Get Logged-in UserCometChat.getLoggedinUser()Promise<User|null>
Send TextCometChat.sendMessage(textMessage)Promise<TextMessage>
Send MediaCometChat.sendMediaMessage(mediaMessage)Promise<MediaMessage>
Fetch MessagesmessagesRequest.fetchPrevious()Promise<BaseMessage[]>
Fetch ConversationsconversationsRequest.fetchNext()Promise<Conversation[]>
Get UserCometChat.getUser(uid)Promise<User>
Get GroupCometChat.getGroup(guid)Promise<Group>
Connection StatusCometChat.getConnectionStatus()string