Skip to main content
Quick Setup Reference
# Install
npm install @cometchat/chat-sdk-javascript

# Initialize (run once at app start)
CometChat.init(APP_ID, appSettings)

# Login (after init)
CometChat.login(UID, AUTH_KEY)  # Dev only
CometChat.login(AUTH_TOKEN)     # Production
Required Credentials: App ID, Region, Auth Key (dev) or Auth Token (prod) Get from: CometChat Dashboard → Your App → API & Auth Keys
This guide walks you through the complete setup process for the CometChat JavaScript SDK, from getting your credentials to sending your first message.

Prerequisites

1

Create a CometChat Account

Sign up for free or log in to your existing account.
2

Create a New App

From the dashboard, click Add New App. Choose a name and select your preferred region.
Region Selection: Choose the region closest to your users for best performance:
  • us - United States
  • eu - Europe
  • in - India
3

Get Your Credentials

Navigate to your app’s API & Auth Keys section and note:
CredentialWhere to FindPurpose
App IDAPI & Auth Keys → App IDIdentifies your app
RegionAPI & Auth Keys → RegionServer location
Auth KeyAPI & Auth Keys → Auth KeyDevelopment login
REST API KeyAPI & Auth Keys → REST API KeyServer-side operations
Security: Never expose your REST API Key in client-side code. Use Auth Key only for development. In production, use Auth Tokens.

Installation

Choose your preferred package manager or CDN:
npm install @cometchat/chat-sdk-javascript

Import the SDK

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

Initialize CometChat

Initialize the SDK once when your application starts. This must be called before any other CometChat methods.
CometChat.init() must be called before login(), sendMessage(), listener registration, or any other SDK method. Calling SDK methods before initialization will fail.
import { CometChat } from "@cometchat/chat-sdk-javascript";

const appID = "YOUR_APP_ID";
const region = "YOUR_REGION"; // "us", "eu", or "in"

const appSettings = new CometChat.AppSettingsBuilder()
  .subscribePresenceForAllUsers()
  .setRegion(region)
  .autoEstablishSocketConnection(true)
  .build();

CometChat.init(appID, appSettings).then(
  () => {
    console.log("CometChat initialized successfully");
    // Now you can login and use other CometChat methods
  },
  (error) => {
    console.log("Initialization failed:", error);
    // Handle initialization error
  }
);
Replace YOUR_APP_ID and YOUR_REGION with your actual credentials from the CometChat Dashboard.

Complete Quick Start

Here’s a complete example that initializes CometChat, logs in a test user, and sends a message:
import { CometChat } from "@cometchat/chat-sdk-javascript";

// Step 1: Configuration
const appID = "YOUR_APP_ID";
const region = "YOUR_REGION";
const authKey = "YOUR_AUTH_KEY";

// Step 2: Initialize
const appSettings = new CometChat.AppSettingsBuilder()
  .subscribePresenceForAllUsers()
  .setRegion(region)
  .autoEstablishSocketConnection(true)
  .build();

CometChat.init(appID, appSettings).then(
  () => {
    console.log("✓ CometChat initialized");
    
    // Step 3: Check if already logged in
    return CometChat.getLoggedinUser();
  }
).then(
  (user) => {
    if (user) {
      console.log("✓ Already logged in as:", user.getName());
      return user;
    }
    
    // Step 4: Login with test user
    console.log("Logging in...");
    return CometChat.login("cometchat-uid-1", authKey);
  }
).then(
  (user) => {
    console.log("✓ Logged in as:", user.getName());
    
    // Step 5: Send a test message
    const message = new CometChat.TextMessage(
      "cometchat-uid-2",
      "Hello from CometChat!",
      CometChat.RECEIVER_TYPE.USER
    );
    
    return CometChat.sendMessage(message);
  }
).then(
  (message) => {
    console.log("✓ Message sent:", message.getText());
    console.log("Setup complete! CometChat is ready to use.");
  }
).catch(
  (error) => {
    console.error("Error:", error);
  }
);
Test Users: CometChat provides 5 pre-created test users: cometchat-uid-1 through cometchat-uid-5. Use these for development and testing.

Configuration Options

AppSettingsBuilder Reference

MethodDescriptionDefault
setRegion(region)Required. Server region (us, eu, in)-
subscribePresenceForAllUsers()Receive online/offline status for all usersDisabled
subscribePresenceForRoles(roles)Receive presence for specific roles only-
subscribePresenceForFriends()Receive presence for friends only-
autoEstablishSocketConnection(bool)Auto-manage WebSocket connectiontrue
setStorageMode(mode)Data persistence modeLOCAL
overrideAdminHost(url)Custom admin URL (dedicated deployment)-
overrideClientHost(url)Custom client URL (dedicated deployment)-

Presence Subscription Options

Choose how to receive user online/offline status updates:
// Best for small apps (< 1000 users)
const appSettings = new CometChat.AppSettingsBuilder()
  .setRegion(region)
  .subscribePresenceForAllUsers()
  .build();
Can be resource-intensive with many users. Consider role-based or friends-only for larger apps.

Storage Modes

Control how CometChat persists data in the browser:
// Session storage - cleared when browser closes
const appSettings = new CometChat.AppSettingsBuilder()
  .setRegion(region)
  .setStorageMode(CometChat.StorageMode.SESSION)
  .build();

// Local storage (default) - persists across sessions
const appSettings = new CometChat.AppSettingsBuilder()
  .setRegion(region)
  .setStorageMode(CometChat.StorageMode.LOCAL)
  .build();
ModePersistenceUse Case
LOCALSurvives browser restartDefault, most apps
SESSIONCleared on tab closeShared computers, kiosks

WebSocket Connection

By default, the SDK automatically manages WebSocket connections. For advanced control:
// Automatic (default) - SDK manages connection
const appSettings = new CometChat.AppSettingsBuilder()
  .setRegion(region)
  .autoEstablishSocketConnection(true)
  .build();

// Manual - you control when to connect/disconnect
const appSettings = new CometChat.AppSettingsBuilder()
  .setRegion(region)
  .autoEstablishSocketConnection(false)
  .build();

// Later, manually connect
CometChat.connect();

// And disconnect when needed
CometChat.disconnect();
Learn more about Manual WebSocket Management.

Framework Integration

Choose your framework below. Each guide follows the same pattern:
  1. Install the SDK
  2. Set up environment variables
  3. Create a CometChat service/provider
  4. Initialize on app load
  5. Use in your components

React Setup

1

Install the SDK

npm install @cometchat/chat-sdk-javascript
2

Create Environment File

Create .env in your project root:
REACT_APP_COMETCHAT_APP_ID=your_app_id
REACT_APP_COMETCHAT_REGION=us
REACT_APP_COMETCHAT_AUTH_KEY=your_auth_key
3

Create CometChat Hook

Create src/hooks/useCometChat.js:
import { useEffect, useState } from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";

const APP_ID = process.env.REACT_APP_COMETCHAT_APP_ID;
const REGION = process.env.REACT_APP_COMETCHAT_REGION;
const AUTH_KEY = process.env.REACT_APP_COMETCHAT_AUTH_KEY;

export function useCometChat() {
  const [isInitialized, setIsInitialized] = useState(false);
  const [user, setUser] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const init = async () => {
      try {
        const appSettings = new CometChat.AppSettingsBuilder()
          .subscribePresenceForAllUsers()
          .setRegion(REGION)
          .autoEstablishSocketConnection(true)
          .build();

        await CometChat.init(APP_ID, appSettings);
        setIsInitialized(true);

        const loggedInUser = await CometChat.getLoggedinUser();
        if (loggedInUser) {
          setUser(loggedInUser);
        }
      } catch (err) {
        setError(err.message);
      }
    };

    init();
  }, []);

  const login = async (uid) => {
    try {
      const loggedInUser = await CometChat.login(uid, AUTH_KEY);
      setUser(loggedInUser);
      return loggedInUser;
    } catch (err) {
      setError(err.message);
      throw err;
    }
  };

  const logout = async () => {
    await CometChat.logout();
    setUser(null);
  };

  return { isInitialized, user, error, login, logout, CometChat };
}
4

Use in Your App

Update src/App.jsx:
import { useCometChat } from "./hooks/useCometChat";

function App() {
  const { isInitialized, user, error, login, logout } = useCometChat();

  if (error) return <div>Error: {error}</div>;
  if (!isInitialized) return <div>Initializing CometChat...</div>;

  if (!user) {
    return (
      <button onClick={() => login("cometchat-uid-1")}>
        Login to Chat
      </button>
    );
  }

  return (
    <div>
      <p>Welcome, {user.getName()}!</p>
      <button onClick={logout}>Logout</button>
      {/* Add your chat components here */}
    </div>
  );
}

export default App;
5

Run Your App

npm start
Open http://localhost:3000 and click “Login to Chat”.

Verify Your Setup

Run this verification script to ensure everything is configured correctly:
import { CometChat } from "@cometchat/chat-sdk-javascript";

async function verifySetup() {
  const APP_ID = "YOUR_APP_ID";
  const REGION = "YOUR_REGION";
  const AUTH_KEY = "YOUR_AUTH_KEY";

  console.log("🔍 Verifying CometChat setup...\n");

  // Step 1: Initialize
  try {
    const appSettings = new CometChat.AppSettingsBuilder()
      .setRegion(REGION)
      .build();

    await CometChat.init(APP_ID, appSettings);
    console.log("✅ Step 1: Initialization successful");
  } catch (error) {
    console.log("❌ Step 1: Initialization failed");
    console.log("   Error:", error.message);
    console.log("   → Check your APP_ID and REGION");
    return;
  }

  // Step 2: Login
  try {
    const user = await CometChat.login("cometchat-uid-1", AUTH_KEY);
    console.log("✅ Step 2: Login successful as", user.getName());
  } catch (error) {
    console.log("❌ Step 2: Login failed");
    console.log("   Error:", error.message);
    console.log("   → Check your AUTH_KEY");
    return;
  }

  // Step 3: Send test message
  try {
    const message = new CometChat.TextMessage(
      "cometchat-uid-2",
      "Test message from setup verification",
      CometChat.RECEIVER_TYPE.USER
    );
    const sent = await CometChat.sendMessage(message);
    console.log("✅ Step 3: Message sent successfully (ID:", sent.getId() + ")");
  } catch (error) {
    console.log("❌ Step 3: Message send failed");
    console.log("   Error:", error.message);
    return;
  }

  // Step 4: Fetch messages
  try {
    const messagesRequest = new CometChat.MessagesRequestBuilder()
      .setUID("cometchat-uid-2")
      .setLimit(5)
      .build();
    const messages = await messagesRequest.fetchPrevious();
    console.log("✅ Step 4: Fetched", messages.length, "messages");
  } catch (error) {
    console.log("❌ Step 4: Fetch messages failed");
    console.log("   Error:", error.message);
    return;
  }

  console.log("\n🎉 All checks passed! CometChat is ready to use.");
}

verifySetup();

Troubleshooting

Cause: App ID or Region doesn’t match your dashboard settings.Solution:
  1. Go to CometChat Dashboard
  2. Select your app
  3. Navigate to API & Auth Keys
  4. Copy the exact App ID and Region
  5. Region must be lowercase: us, eu, or in
// ❌ Wrong
const region = "US";
const region = "United States";

// ✅ Correct
const region = "us";
Cause: SDK not imported or loaded before use.Solution for ES Modules:
// Make sure import is at the top of your file
import { CometChat } from "@cometchat/chat-sdk-javascript";
Solution for CDN:
<!-- Script must load before your code -->
<script src="https://unpkg.com/@cometchat/chat-sdk-javascript/CometChat.js"></script>
<script>
  // CometChat is now available
  console.log(CometChat);
</script>
Cause: CometChat requires browser APIs (window, localStorage) not available during server-side rendering.Solution: Use dynamic imports and ensure code runs only on client:
// Next.js App Router
"use client";

useEffect(() => {
  const init = async () => {
    const { CometChat } = await import("@cometchat/chat-sdk-javascript");
    // Initialize here
  };
  init();
}, []);
// Nuxt - use .client.js suffix
// plugins/cometchat.client.js
Cause: Using wrong Auth Key or REST API Key instead of Auth Key.Solution:
  1. Go to Dashboard → API & Auth Keys
  2. Use the Auth Key (not REST API Key)
  3. Ensure no extra spaces when copying
Auth Key is for development only. Use Auth Tokens in production.
Cause: Trying to login with a UID that hasn’t been created.Solution: Use test users or create the user first:
// Option 1: Use pre-created test users
CometChat.login("cometchat-uid-1", authKey);

// Option 2: Create user first (development only)
const user = new CometChat.User("new-user-id");
user.setName("New User");
await CometChat.createUser(user, authKey);
await CometChat.login("new-user-id", authKey);
Cause: Network restrictions, firewall, or VPN blocking WebSocket connections.Solution:
  1. Check if WebSockets are blocked by your network
  2. Try disabling VPN temporarily
  3. Check browser console for connection errors
  4. Verify autoEstablishSocketConnection(true) is set
// Monitor connection status
CometChat.addConnectionListener(
  "CONNECTION_LISTENER",
  new CometChat.ConnectionListener({
    onConnected: () => console.log("Connected"),
    onDisconnected: () => console.log("Disconnected"),
    inConnecting: () => console.log("Connecting...")
  })
);
Cause: Message listener not registered or using wrong listener ID.Solution:
// Register listener AFTER login
CometChat.addMessageListener(
  "UNIQUE_LISTENER_ID", // Must be unique
  new CometChat.MessageListener({
    onTextMessageReceived: (message) => {
      console.log("Message received:", message);
    }
  })
);
Listeners must be registered after successful login and use unique IDs.

Migration from v3

Upgrading from v3? See the complete Migration Guide for step-by-step instructions.
Key changes in v4:
  • New package name: @cometchat/chat-sdk-javascript
  • Updated initialization with AppSettingsBuilder
  • Improved TypeScript support
  • New features: reactions, interactive messages, enhanced presence

Next Steps