Quick Reference // Development: Login with Auth Key (NOT for production)
await CometChat . login ( "USER_UID" , "AUTH_KEY" );
// Production: Login with Auth Token (generated server-side)
await CometChat . login ( "AUTH_TOKEN_FROM_SERVER" );
// Check if already logged in
const user = await CometChat . getLoggedinUser ();
if ( user ) console . log ( "Already logged in:" , user . getName ());
// Logout
await CometChat . logout ();
Decision:
Building/testing? → Use Auth Key with test users (cometchat-uid-1 to cometchat-uid-5)
Going to production? → Generate Auth Tokens server-side via REST API
CometChat requires users to be authenticated before they can send or receive messages. This guide covers the authentication flow and best practices for both development and production environments.
CometChat does not handle user management. You manage user registration and login in your app. Once a user logs into your app, you programmatically log them into CometChat.
Authentication Flow
Choose Your Authentication Method
Auth Key (Development) Simple setup for prototyping and testing. The Auth Key is used directly in client code. Use for: POC, development, testing
Auth Token (Production) Secure authentication where tokens are generated server-side. Auth Key never exposed to clients. Use for: Production applications
Create a User
Before logging in, users must exist in CometChat.
Dashboard (Testing)
REST API (Production)
SDK (On-the-fly)
For testing, create users manually in the CometChat Dashboard under Users . We provide 5 test users: cometchat-uid-1 through cometchat-uid-5
For production, create users via the Create User API when users sign up in your app. Create users directly from the client (development only): const authKey = "YOUR_AUTH_KEY" ;
const uid = "user1" ;
const name = "Kevin" ;
const user = new CometChat . User ( uid );
user . setName ( name );
CometChat . createUser ( user , authKey ). then (
( user ) => console . log ( "User created:" , user ),
( error ) => console . log ( "Error:" , error )
);
UID Requirements: Alphanumeric characters, underscores, and hyphens only. No spaces, punctuation, or special characters.
Login with Auth Key
Development Only: Auth Key login exposes your key in client code. Use Auth Token for production.
The simplest way to authenticate during development:
JavaScript
TypeScript
Async/Await
const UID = "cometchat-uid-1" ;
const authKey = "YOUR_AUTH_KEY" ;
// Check if already logged in
CometChat . getLoggedinUser (). then (
( user ) => {
if ( ! user ) {
// Not logged in, proceed with login
CometChat . login ( UID , authKey ). then (
( user ) => {
console . log ( "Login successful:" , user );
},
( error ) => {
console . log ( "Login failed:" , error );
}
);
} else {
console . log ( "Already logged in:" , user );
}
},
( error ) => {
console . log ( "Error:" , error );
}
);
const UID : string = "cometchat-uid-1" ;
const authKey : string = "YOUR_AUTH_KEY" ;
CometChat . getLoggedinUser (). then (
( user : CometChat . User | null ) => {
if ( ! user ) {
CometChat . login ( UID , authKey ). then (
( user : CometChat . User ) => {
console . log ( "Login successful:" , user );
},
( error : CometChat . CometChatException ) => {
console . log ( "Login failed:" , error );
}
);
} else {
console . log ( "Already logged in:" , user );
}
},
( error : CometChat . CometChatException ) => {
console . log ( "Error:" , error );
}
);
const UID = "cometchat-uid-1" ;
const authKey = "YOUR_AUTH_KEY" ;
async function loginWithAuthKey () {
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 , authKey );
console . log ( "Login successful:" , user . getName ());
return user ;
} catch ( error ) {
console . error ( "Login failed:" , error );
throw error ;
}
}
loginWithAuthKey ();
Parameter Description UIDThe unique identifier of the user to log in authKeyYour CometChat Auth Key from the dashboard
Login with Auth Token
Recommended for Production: Auth Tokens are generated server-side, keeping your Auth Key secure.
How It Works
User signs up in your app
Create the user in CometChat via REST API
Send token to client
Your server returns the Auth Token to your client app
Login with token
Use the token to log in via the SDK
Client-Side Login
JavaScript
TypeScript
Async/Await
const authToken = "AUTH_TOKEN_FROM_YOUR_SERVER" ;
CometChat . getLoggedinUser (). then (
( user ) => {
if ( ! user ) {
CometChat . login ( authToken ). then (
( user ) => {
console . log ( "Login successful:" , user );
},
( error ) => {
console . log ( "Login failed:" , error );
}
);
} else {
console . log ( "Already logged in:" , user );
}
},
( error ) => {
console . log ( "Error:" , error );
}
);
const authToken : string = "AUTH_TOKEN_FROM_YOUR_SERVER" ;
CometChat . getLoggedinUser (). then (
( user : CometChat . User | null ) => {
if ( ! user ) {
CometChat . login ( authToken ). then (
( user : CometChat . User ) => {
console . log ( "Login successful:" , user );
},
( error : CometChat . CometChatException ) => {
console . log ( "Login failed:" , error );
}
);
} else {
console . log ( "Already logged in:" , user );
}
},
( error : CometChat . CometChatException ) => {
console . log ( "Error:" , error );
}
);
async function loginWithAuthToken ( authToken ) {
try {
// Check if already logged in
let user = await CometChat . getLoggedinUser ();
if ( user ) {
console . log ( "Already logged in:" , user . getName ());
return user ;
}
// Login with token
user = await CometChat . login ( authToken );
console . log ( "Login successful:" , user . getName ());
return user ;
} catch ( error ) {
console . error ( "Login failed:" , error );
throw error ;
}
}
// Get token from your server and login
async function authenticateUser ( userId ) {
// 1. Get auth token from your backend
const response = await fetch ( `/api/cometchat/token/ ${ userId } ` );
const { authToken } = await response . json ();
// 2. Login to CometChat
return loginWithAuthToken ( authToken );
}
Parameter Description authTokenThe Auth Token generated by your server
Check Login Status
The SDK maintains the user session. Check if a user is already logged in before calling login():
CometChat . getLoggedinUser (). then (
( user ) => {
if ( user ) {
console . log ( "User is logged in:" , user . getName ());
} else {
console . log ( "No user logged in" );
// Proceed with login
}
},
( error ) => {
console . log ( "Error checking login status:" , error );
}
);
async function checkLoginStatus () {
try {
const user = await CometChat . getLoggedinUser ();
if ( user ) {
console . log ( "User is logged in:" , user . getName ());
return user ;
} else {
console . log ( "No user logged in" );
return null ;
}
} catch ( error ) {
console . log ( "Error checking login status:" , error );
throw error ;
}
}
You only need to call login() once. The SDK persists the session, so users remain logged in across page refreshes until you call logout().
Logout
Log out the user when they sign out of your app:
JavaScript
TypeScript
Async/Await
CometChat . logout (). then (
() => {
console . log ( "Logout successful" );
},
( error ) => {
console . log ( "Logout failed:" , error );
}
);
CometChat . logout (). then (
() => {
console . log ( "Logout successful" );
},
( error : CometChat . CometChatException ) => {
console . log ( "Logout failed:" , error );
}
);
async function logout () {
try {
await CometChat . logout ();
console . log ( "Logout successful" );
// Redirect to login page or update UI
} catch ( error ) {
console . error ( "Logout failed:" , error );
}
}
Always call CometChat.logout() when users sign out of your app. This clears the local session and stops real-time event delivery.
Server-Side Token Generation
Here’s how to generate Auth Tokens on your backend:
// server.js
const express = require ( "express" );
const fetch = require ( "node-fetch" );
const app = express ();
const APP_ID = process . env . COMETCHAT_APP_ID ;
const REGION = process . env . COMETCHAT_REGION ;
const API_KEY = process . env . COMETCHAT_API_KEY ; // REST API Key
// Generate auth token for a user
app . post ( "/api/cometchat/token/:uid" , async ( req , res ) => {
const { uid } = req . params ;
try {
const response = await fetch (
`https:// ${ APP_ID } .api- ${ REGION } .cometchat.io/v3/users/ ${ uid } /auth_tokens` ,
{
method: "POST" ,
headers: {
"Content-Type" : "application/json" ,
"apiKey" : API_KEY
}
}
);
const data = await response . json ();
if ( data . data ?. authToken ) {
res . json ({ authToken: data . data . authToken });
} else {
res . status ( 400 ). json ({ error: "Failed to generate token" });
}
} catch ( error ) {
res . status ( 500 ). json ({ error: error . message });
}
});
// Create user and generate token
app . post ( "/api/cometchat/users" , async ( req , res ) => {
const { uid , name , avatar } = req . body ;
try {
// Create user
await fetch (
`https:// ${ APP_ID } .api- ${ REGION } .cometchat.io/v3/users` ,
{
method: "POST" ,
headers: {
"Content-Type" : "application/json" ,
"apiKey" : API_KEY
},
body: JSON . stringify ({ uid , name , avatar })
}
);
// Generate token
const tokenResponse = await fetch (
`https:// ${ APP_ID } .api- ${ REGION } .cometchat.io/v3/users/ ${ uid } /auth_tokens` ,
{
method: "POST" ,
headers: {
"Content-Type" : "application/json" ,
"apiKey" : API_KEY
}
}
);
const tokenData = await tokenResponse . json ();
res . json ({ authToken: tokenData . data . authToken });
} catch ( error ) {
res . status ( 500 ). json ({ error: error . message });
}
});
app . listen ( 3000 );
# server.py
from flask import Flask, jsonify, request
import requests
import os
app = Flask( __name__ )
APP_ID = os.environ.get( "COMETCHAT_APP_ID" )
REGION = os.environ.get( "COMETCHAT_REGION" )
API_KEY = os.environ.get( "COMETCHAT_API_KEY" )
BASE_URL = f "https:// { APP_ID } .api- { REGION } .cometchat.io/v3"
@app.route ( "/api/cometchat/token/<uid>" , methods = [ "POST" ])
def generate_token ( uid ):
response = requests.post(
f " { BASE_URL } /users/ { uid } /auth_tokens" ,
headers = {
"Content-Type" : "application/json" ,
"apiKey" : API_KEY
}
)
data = response.json()
if "data" in data and "authToken" in data[ "data" ]:
return jsonify({ "authToken" : data[ "data" ][ "authToken" ]})
return jsonify({ "error" : "Failed to generate token" }), 400
if __name__ == "__main__" :
app.run( port = 3000 )
User Object
On successful login, you receive a User object with the following properties:
Property Type Description uidstring Unique identifier namestring Display name avatarstring Profile picture URL statusstring online or offlinerolestring User role for access control metadataobject Custom data lastActiveAtnumber Unix timestamp of last activity
Access user properties:
CometChat . login ( UID , authKey ). then (( user ) => {
console . log ( "UID:" , user . getUid ());
console . log ( "Name:" , user . getName ());
console . log ( "Avatar:" , user . getAvatar ());
console . log ( "Status:" , user . getStatus ());
});
async function loginAndGetUserInfo ( UID , authKey ) {
try {
const user = await CometChat . login ( UID , authKey );
console . log ( "UID:" , user . getUid ());
console . log ( "Name:" , user . getName ());
console . log ( "Avatar:" , user . getAvatar ());
console . log ( "Status:" , user . getStatus ());
return user ;
} catch ( error ) {
console . log ( "Login failed:" , error );
throw error ;
}
}
Listen for Login Events
Monitor authentication state changes across devices:
const listenerID = "AUTH_LISTENER" ;
CometChat . addLoginListener (
listenerID ,
new CometChat . LoginListener ({
loginSuccess : ( user ) => {
console . log ( "User logged in:" , user );
},
logoutSuccess : () => {
console . log ( "User logged out" );
},
})
);
// Remove listener when no longer needed
CometChat . removeLoginListener ( listenerID );
Learn more about Login Listeners .
Best Practices
Always check login status first
Before calling login(), use getLoggedinUser() to check if a session exists. This prevents unnecessary API calls and potential errors.
Use Auth Tokens in production
Never expose your Auth Key in production client code. Generate Auth Tokens server-side and pass them to your client.
Auth Tokens can expire. Implement token refresh logic in your app to generate new tokens when needed.
Sync logout with your app
Call CometChat.logout() when users log out of your app to properly clean up the CometChat session.
Troubleshooting
'User does not exist' error
The UID you’re trying to login with hasn’t been created in CometChat. Solutions:
Use test users: cometchat-uid-1 through cometchat-uid-5
Create the user first via REST API or SDK
Check for typos in the UID
'Auth Key is invalid' error
Causes:
Using REST API Key instead of Auth Key
Auth Key has extra spaces
Auth Key is from a different app
Solution: Copy the Auth Key directly from Dashboard → API & Auth Keys
'Auth Token is invalid or expired' error
Auth Tokens have an expiration time (default: 15 minutes). Solutions:
Generate a new token from your server
Increase token expiration in Dashboard settings
Implement token refresh logic in your app
Login works but no messages received
Causes:
Message listeners not registered
WebSocket connection not established
Solutions:
Register listeners after successful login
Check autoEstablishSocketConnection(true) in app settings
Add a connection listener to debug
Next Steps