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
Create a CometChat Account
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
Get Your Credentials
Navigate to your app’s API & Auth Keys section and note: Credential Where to Find Purpose App ID API & Auth Keys → App ID Identifies your app Region API & Auth Keys → Region Server location Auth Key API & Auth Keys → Auth Key Development login REST API Key API & Auth Keys → REST API Key Server-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
yarn add @cometchat/chat-sdk-javascript
pnpm add @cometchat/chat-sdk-javascript
< script
type = "text/javascript"
src = "https://unpkg.com/@cometchat/chat-sdk-javascript/CometChat.js" >
</ script >
Import the SDK
ES Modules
CommonJS
CDN (Global)
import { CometChat } from "@cometchat/chat-sdk-javascript" ;
const { CometChat } = require ( "@cometchat/chat-sdk-javascript" );
// CometChat is available globally after script loads
window . CometChat
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.
JavaScript
TypeScript
Async/Await
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
}
);
import { CometChat } from "@cometchat/chat-sdk-javascript" ;
const appID : string = "YOUR_APP_ID" ;
const region : string = "YOUR_REGION" ;
const appSettings : CometChat . AppSettings = new CometChat . AppSettingsBuilder ()
. subscribePresenceForAllUsers ()
. setRegion ( region )
. autoEstablishSocketConnection ( true )
. build ();
CometChat . init ( appID , appSettings ). then (
( success : boolean ) : void => {
console . log ( "CometChat initialized successfully" , success );
},
( error : CometChat . CometChatException ) : void => {
console . log ( "Initialization failed:" , error );
}
);
import { CometChat } from "@cometchat/chat-sdk-javascript" ;
async function initializeCometChat () {
const appID = "YOUR_APP_ID" ;
const region = "YOUR_REGION" ;
const appSettings = new CometChat . AppSettingsBuilder ()
. subscribePresenceForAllUsers ()
. setRegion ( region )
. autoEstablishSocketConnection ( true )
. build ();
try {
await CometChat . init ( appID , appSettings );
console . log ( "CometChat initialized successfully" );
return true ;
} catch ( error ) {
console . log ( "Initialization failed:" , error );
return false ;
}
}
// Call on app startup
initializeCometChat ();
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
Method Description Default setRegion(region)Required. Server region (us, eu, in)- subscribePresenceForAllUsers()Receive online/offline status for all users Disabled subscribePresenceForRoles(roles)Receive presence for specific roles only - subscribePresenceForFriends()Receive presence for friends only - autoEstablishSocketConnection(bool)Auto-manage WebSocket connection truesetStorageMode(mode)Data persistence mode LOCALoverrideAdminHost(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:
All Users
By Role
Friends Only
No Presence
// 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.
// Best for apps with user tiers
const appSettings = new CometChat . AppSettingsBuilder ()
. setRegion ( region )
. subscribePresenceForRoles ([ "premium" , "moderator" , "admin" ])
. build ();
// Best for social apps
const appSettings = new CometChat . AppSettingsBuilder ()
. setRegion ( region )
. subscribePresenceForFriends ()
. build ();
// Minimal setup - no presence tracking
const appSettings = new CometChat . AppSettingsBuilder ()
. setRegion ( region )
. build ();
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 ();
Mode Persistence Use Case LOCALSurvives browser restart Default, most apps SESSIONCleared on tab close Shared 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:
Install the SDK
Set up environment variables
Create a CometChat service/provider
Initialize on app load
Use in your components
React
Next.js (App Router)
Next.js (Pages Router)
Vue.js
Nuxt.js
Angular
Vanilla JS
React Setup
Install the SDK
npm install @cometchat/chat-sdk-javascript
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
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 };
}
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 ;
Next.js 13+ App Router Setup CometChat requires browser APIs. Use dynamic imports and "use client" directive to avoid SSR issues.
Install the SDK
npm install @cometchat/chat-sdk-javascript
Create Environment File
Create .env.local in your project root: NEXT_PUBLIC_COMETCHAT_APP_ID = your_app_id
NEXT_PUBLIC_COMETCHAT_REGION = us
NEXT_PUBLIC_COMETCHAT_AUTH_KEY = your_auth_key
Create CometChat Provider
Create app/providers/CometChatProvider.jsx: "use client" ;
import { createContext , useContext , useEffect , useState } from "react" ;
const CometChatContext = createContext ( null );
export function CometChatProvider ({ children }) {
const [ cometChat , setCometChat ] = useState ( null );
const [ isReady , setIsReady ] = useState ( false );
const [ error , setError ] = useState ( null );
useEffect (() => {
const initCometChat = async () => {
try {
// Dynamic import to avoid SSR issues
const { CometChat } = await import ( "@cometchat/chat-sdk-javascript" );
const appSettings = new CometChat . AppSettingsBuilder ()
. subscribePresenceForAllUsers ()
. setRegion ( process . env . NEXT_PUBLIC_COMETCHAT_REGION )
. autoEstablishSocketConnection ( true )
. build ();
await CometChat . init (
process . env . NEXT_PUBLIC_COMETCHAT_APP_ID ,
appSettings
);
setCometChat ( CometChat );
setIsReady ( true );
} catch ( err ) {
setError ( err . message );
}
};
initCometChat ();
}, []);
if ( error ) return < div > CometChat Error: { error } </ div > ;
if ( ! isReady ) return < div > Loading CometChat... </ div > ;
return (
< CometChatContext.Provider value = { cometChat } >
{ children }
</ CometChatContext.Provider >
);
}
export const useCometChat = () => useContext ( CometChatContext );
Add Provider to Layout
Update app/layout.jsx: import { CometChatProvider } from "./providers/CometChatProvider" ;
export default function RootLayout ({ children }) {
return (
< html lang = "en" >
< body >
< CometChatProvider >
{ children }
</ CometChatProvider >
</ body >
</ html >
);
}
Use in Your Pages
Create app/chat/page.jsx: "use client" ;
import { useCometChat } from "../providers/CometChatProvider" ;
import { useState } from "react" ;
export default function ChatPage () {
const CometChat = useCometChat ();
const [ user , setUser ] = useState ( null );
const handleLogin = async () => {
try {
const loggedInUser = await CometChat . login (
"cometchat-uid-1" ,
process . env . NEXT_PUBLIC_COMETCHAT_AUTH_KEY
);
setUser ( loggedInUser );
} catch ( error ) {
console . error ( "Login failed:" , error );
}
};
if ( ! user ) {
return < button onClick = { handleLogin } > Login to Chat </ button > ;
}
return < div > Welcome, { user . getName () } ! </ div > ;
}
Next.js Pages Router Setup
Install the SDK
npm install @cometchat/chat-sdk-javascript
Create Environment File
Create .env.local: NEXT_PUBLIC_COMETCHAT_APP_ID = your_app_id
NEXT_PUBLIC_COMETCHAT_REGION = us
NEXT_PUBLIC_COMETCHAT_AUTH_KEY = your_auth_key
Create CometChat Context
Create lib/cometchat.js: import { createContext , useContext } from "react" ;
export const CometChatContext = createContext ( null );
export const useCometChat = () => useContext ( CometChatContext );
Initialize in _app.js
Update pages/_app.js: import { useEffect , useState } from "react" ;
import { CometChatContext } from "../lib/cometchat" ;
export default function App ({ Component , pageProps }) {
const [ cometChat , setCometChat ] = useState ( null );
useEffect (() => {
const init = async () => {
const { CometChat } = await import ( "@cometchat/chat-sdk-javascript" );
const appSettings = new CometChat . AppSettingsBuilder ()
. subscribePresenceForAllUsers ()
. setRegion ( process . env . NEXT_PUBLIC_COMETCHAT_REGION )
. autoEstablishSocketConnection ( true )
. build ();
await CometChat . init (
process . env . NEXT_PUBLIC_COMETCHAT_APP_ID ,
appSettings
);
setCometChat ( CometChat );
};
init ();
}, []);
if ( ! cometChat ) return < div > Loading CometChat... </ div > ;
return (
< CometChatContext.Provider value = { cometChat } >
< Component { ... pageProps } />
</ CometChatContext.Provider >
);
}
Use in Your Pages
Create pages/chat.js: import { useState } from "react" ;
import { useCometChat } from "../lib/cometchat" ;
export default function ChatPage () {
const CometChat = useCometChat ();
const [ user , setUser ] = useState ( null );
const handleLogin = async () => {
const loggedInUser = await CometChat . login (
"cometchat-uid-1" ,
process . env . NEXT_PUBLIC_COMETCHAT_AUTH_KEY
);
setUser ( loggedInUser );
};
if ( ! user ) {
return < button onClick = { handleLogin } > Login to Chat </ button > ;
}
return < div > Welcome, { user . getName () } ! </ div > ;
}
Vue.js Setup
Install the SDK
npm install @cometchat/chat-sdk-javascript
Create Environment File
Create .env in your project root: VITE_COMETCHAT_APP_ID = your_app_id
VITE_COMETCHAT_REGION = us
VITE_COMETCHAT_AUTH_KEY = your_auth_key
Create CometChat Plugin
Create src/plugins/cometchat.js: import { CometChat } from "@cometchat/chat-sdk-javascript" ;
export default {
install : async ( app ) => {
const appSettings = new CometChat . AppSettingsBuilder ()
. subscribePresenceForAllUsers ()
. setRegion ( import . meta . env . VITE_COMETCHAT_REGION )
. autoEstablishSocketConnection ( true )
. build ();
await CometChat . init (
import . meta . env . VITE_COMETCHAT_APP_ID ,
appSettings
);
// Make CometChat available globally
app . config . globalProperties . $CometChat = CometChat ;
app . provide ( "CometChat" , CometChat );
} ,
} ;
Register Plugin in main.js
Update src/main.js: import { createApp } from "vue" ;
import App from "./App.vue" ;
import CometChatPlugin from "./plugins/cometchat" ;
const app = createApp ( App );
// Initialize CometChat before mounting
CometChatPlugin . install ( app ). then (() => {
app . mount ( "#app" );
});
Use in Your Components
Update src/App.vue: < template >
< div v-if = " error " > Error: {{ error }} </ div >
< div v-else-if = " ! user " >
< button @ click = " login " > Login to Chat </ button >
</ div >
< div v-else >
< p > Welcome, {{ user . getName () }}! </ p >
< button @ click = " logout " > Logout </ button >
</ div >
</ template >
< script setup >
import { ref , inject , onMounted } from "vue" ;
const CometChat = inject ( "CometChat" );
const user = ref ( null );
const error = ref ( null );
onMounted ( async () => {
// Check for existing session
const loggedInUser = await CometChat . getLoggedinUser ();
if ( loggedInUser ) {
user . value = loggedInUser ;
}
});
const login = async () => {
try {
user . value = await CometChat . login (
"cometchat-uid-1" ,
import . meta . env . VITE_COMETCHAT_AUTH_KEY
);
} catch ( err ) {
error . value = err . message ;
}
};
const logout = async () => {
await CometChat . logout ();
user . value = null ;
};
</ script >
Nuxt 3 Setup Use the .client.js suffix for plugins to ensure they only run on the client side.
Install the SDK
npm install @cometchat/chat-sdk-javascript
Configure Environment Variables
Update nuxt.config.ts: export default defineNuxtConfig ({
runtimeConfig: {
public: {
cometchatAppId: process . env . COMETCHAT_APP_ID ,
cometchatRegion: process . env . COMETCHAT_REGION ,
cometchatAuthKey: process . env . COMETCHAT_AUTH_KEY ,
},
} ,
}) ;
Create .env: COMETCHAT_APP_ID = your_app_id
COMETCHAT_REGION = us
COMETCHAT_AUTH_KEY = your_auth_key
Create CometChat Plugin
Create plugins/cometchat.client.js: export default defineNuxtPlugin ( async () => {
const { CometChat } = await import ( "@cometchat/chat-sdk-javascript" );
const config = useRuntimeConfig ();
const appSettings = new CometChat . AppSettingsBuilder ()
. subscribePresenceForAllUsers ()
. setRegion ( config . public . cometchatRegion )
. autoEstablishSocketConnection ( true )
. build ();
await CometChat . init ( config . public . cometchatAppId , appSettings );
return {
provide: {
CometChat ,
},
};
} ) ;
Create a Composable (Optional)
Create composables/useCometChat.js: export const useCometChatAuth = () => {
const { $CometChat } = useNuxtApp ();
const config = useRuntimeConfig ();
const user = useState ( "cometchat-user" , () => null );
const login = async ( uid ) => {
user . value = await $CometChat . login ( uid , config . public . cometchatAuthKey );
return user . value ;
};
const logout = async () => {
await $CometChat . logout ();
user . value = null ;
};
const checkSession = async () => {
user . value = await $CometChat . getLoggedinUser ();
return user . value ;
};
return { user , login , logout , checkSession };
};
Use in Your Pages
Create pages/chat.vue: < template >
< div >
< div v-if = " ! user " >
< button @ click = " handleLogin " > Login to Chat </ button >
</ div >
< div v-else >
< p > Welcome, {{ user . getName () }}! </ p >
< button @ click = " handleLogout " > Logout </ button >
</ div >
</ div >
</ template >
< script setup >
const { user , login , logout , checkSession } = useCometChatAuth ();
onMounted ( async () => {
await checkSession ();
});
const handleLogin = async () => {
await login ( "cometchat-uid-1" );
};
const handleLogout = async () => {
await logout ();
};
</ script >
Angular Setup
Install the SDK
npm install @cometchat/chat-sdk-javascript
Configure Environment
Update src/environments/environment.ts: export const environment = {
production: false ,
cometchatAppId: "your_app_id" ,
cometchatRegion: "us" ,
cometchatAuthKey: "your_auth_key" ,
};
Create CometChat Service
Generate and update src/app/services/cometchat.service.ts: ng generate service services/cometchat
import { Injectable } from "@angular/core" ;
import { CometChat } from "@cometchat/chat-sdk-javascript" ;
import { environment } from "../../environments/environment" ;
@ Injectable ({
providedIn: "root" ,
})
export class CometChatService {
private initialized = false ;
async init () : Promise < boolean > {
if ( this . initialized ) return true ;
const appSettings = new CometChat . AppSettingsBuilder ()
. subscribePresenceForAllUsers ()
. setRegion ( environment . cometchatRegion )
. autoEstablishSocketConnection ( true )
. build ();
try {
await CometChat . init ( environment . cometchatAppId , appSettings );
this . initialized = true ;
return true ;
} catch ( error ) {
console . error ( "CometChat init failed:" , error );
return false ;
}
}
async login ( uid : string ) : Promise < CometChat . User > {
return CometChat . login ( uid , environment . cometchatAuthKey );
}
async getLoggedInUser () : Promise < CometChat . User | null > {
return CometChat . getLoggedinUser ();
}
async logout () : Promise < void > {
return CometChat . logout ();
}
getCometChat () {
return CometChat ;
}
}
Initialize in App Component
Update src/app/app.component.ts: import { Component , OnInit } from "@angular/core" ;
import { CometChatService } from "./services/cometchat.service" ;
@ Component ({
selector: "app-root" ,
template: `
<div *ngIf="!isReady">Initializing CometChat...</div>
<div *ngIf="isReady && !user">
<button (click)="login()">Login to Chat</button>
</div>
<div *ngIf="user">
<p>Welcome, {{ user.getName() }}!</p>
<button (click)="logout()">Logout</button>
<router-outlet></router-outlet>
</div>
` ,
})
export class AppComponent implements OnInit {
isReady = false ;
user : any = null ;
constructor ( private cometChatService : CometChatService ) {}
async ngOnInit () {
this . isReady = await this . cometChatService . init ();
if ( this . isReady ) {
this . user = await this . cometChatService . getLoggedInUser ();
}
}
async login () {
try {
this . user = await this . cometChatService . login ( "cometchat-uid-1" );
} catch ( error ) {
console . error ( "Login failed:" , error );
}
}
async logout () {
await this . cometChatService . logout ();
this . user = null ;
}
}
Vanilla JavaScript Setup
Create HTML File
Create index.html: <! DOCTYPE html >
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< title > CometChat Demo </ title >
< script src = "https://unpkg.com/@cometchat/chat-sdk-javascript/CometChat.js" ></ script >
< style >
body { font-family : Arial , sans-serif ; padding : 20 px ; }
button { padding : 10 px 20 px ; cursor : pointer ; }
#chat { display : none ; }
#messages { border : 1 px solid #ccc ; padding : 10 px ; height : 300 px ; overflow-y : auto ; margin : 10 px 0 ; }
.message { padding : 5 px ; margin : 5 px 0 ; background : #f0f0f0 ; border-radius : 5 px ; }
</ style >
</ head >
< body >
< div id = "app" >
< div id = "loading" > Initializing CometChat... </ div >
< div id = "login" style = "display: none;" >
< h2 > CometChat Demo </ h2 >
< button onclick = " login ()" > Login as Test User </ button >
</ div >
< div id = "chat" style = "display: none;" >
< h2 > Welcome, < span id = "username" ></ span > ! </ h2 >
< button onclick = " logout ()" > Logout </ button >
< hr >
< div id = "messages" ></ div >
< input type = "text" id = "messageInput" placeholder = "Type a message..." style = "width: 70%;" >
< button onclick = " sendMessage ()" > Send </ button >
</ div >
</ div >
< script src = "app.js" ></ script >
</ body >
</ html >
Create JavaScript File
Create app.js: // Configuration - Replace with your credentials
const APP_ID = "YOUR_APP_ID" ;
const REGION = "YOUR_REGION" ;
const AUTH_KEY = "YOUR_AUTH_KEY" ;
// Initialize CometChat
async function init () {
const appSettings = new CometChat . AppSettingsBuilder ()
. subscribePresenceForAllUsers ()
. setRegion ( REGION )
. autoEstablishSocketConnection ( true )
. build ();
try {
await CometChat . init ( APP_ID , appSettings );
console . log ( "CometChat initialized" );
// Check for existing session
const user = await CometChat . getLoggedinUser ();
if ( user ) {
showChat ( user );
} else {
showLogin ();
}
} catch ( error ) {
console . error ( "Init failed:" , error );
document . getElementById ( "loading" ). textContent = "Failed to initialize: " + error . message ;
}
}
async function login () {
try {
const user = await CometChat . login ( "cometchat-uid-1" , AUTH_KEY );
showChat ( user );
setupMessageListener ();
} catch ( error ) {
console . error ( "Login failed:" , error );
alert ( "Login failed: " + error . message );
}
}
async function logout () {
await CometChat . logout ();
CometChat . removeMessageListener ( "MESSAGE_LISTENER" );
showLogin ();
}
async function sendMessage () {
const text = document . getElementById ( "messageInput" ). value . trim ();
if ( ! text ) return ;
const message = new CometChat . TextMessage (
"cometchat-uid-2" ,
text ,
CometChat . RECEIVER_TYPE . USER
);
try {
const sent = await CometChat . sendMessage ( message );
appendMessage ( sent , true );
document . getElementById ( "messageInput" ). value = "" ;
} catch ( error ) {
console . error ( "Send failed:" , error );
}
}
function setupMessageListener () {
CometChat . addMessageListener (
"MESSAGE_LISTENER" ,
new CometChat . MessageListener ({
onTextMessageReceived : ( message ) => {
appendMessage ( message , false );
},
})
);
}
function appendMessage ( message , isSent ) {
const messagesDiv = document . getElementById ( "messages" );
const messageEl = document . createElement ( "div" );
messageEl . className = "message" ;
messageEl . style . textAlign = isSent ? "right" : "left" ;
messageEl . style . background = isSent ? "#007bff" : "#f0f0f0" ;
messageEl . style . color = isSent ? "white" : "black" ;
messageEl . textContent = message . getText ();
messagesDiv . appendChild ( messageEl );
messagesDiv . scrollTop = messagesDiv . scrollHeight ;
}
function showLogin () {
document . getElementById ( "loading" ). style . display = "none" ;
document . getElementById ( "login" ). style . display = "block" ;
document . getElementById ( "chat" ). style . display = "none" ;
}
function showChat ( user ) {
document . getElementById ( "loading" ). style . display = "none" ;
document . getElementById ( "login" ). style . display = "none" ;
document . getElementById ( "chat" ). style . display = "block" ;
document . getElementById ( "username" ). textContent = user . getName ();
}
// Handle Enter key in message input
document . addEventListener ( "DOMContentLoaded" , () => {
document . getElementById ( "messageInput" )?. addEventListener ( "keypress" , ( e ) => {
if ( e . key === "Enter" ) sendMessage ();
});
});
// Start initialization
init ();
Run Your App
Open index.html in a browser, or use a local server: Open http://localhost:3000 and click “Login as Test User”.
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
'App not found' or 'Invalid App ID' error
Cause: App ID or Region doesn’t match your dashboard settings.Solution:
Go to CometChat Dashboard
Select your app
Navigate to API & Auth Keys
Copy the exact App ID and Region
Region must be lowercase: us, eu, or in
// ❌ Wrong
const region = "US" ;
const region = "United States" ;
// ✅ Correct
const region = "us" ;
'CometChat is not defined' error
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 >
SSR/Hydration errors in Next.js or Nuxt
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
'Auth Key is invalid' error
Cause: Using wrong Auth Key or REST API Key instead of Auth Key.Solution:
Go to Dashboard → API & Auth Keys
Use the Auth Key (not REST API Key)
Ensure no extra spaces when copying
Auth Key is for development only. Use Auth Tokens in production.
'User does not exist' error
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 );
WebSocket connection issues
Cause: Network restrictions, firewall, or VPN blocking WebSocket connections.Solution:
Check if WebSockets are blocked by your network
Try disabling VPN temporarily
Check browser console for connection errors
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..." )
})
);
Messages not being received in real-time
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