Skip to main content
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.
For testing, create users manually in the CometChat Dashboard under Users.
We provide 5 test users: cometchat-uid-1 through cometchat-uid-5
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:
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);
  }
);
ParameterDescription
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

1

User signs up in your app

Create the user in CometChat via REST API
2

Generate Auth Token

Call the Create Auth Token API from your server
3

Send token to client

Your server returns the Auth Token to your client app
4

Login with token

Use the token to log in via the SDK

Client-Side Login

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);
  }
);
ParameterDescription
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);
  }
);
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:
CometChat.logout().then(
  () => {
    console.log("Logout successful");
  },
  (error) => {
    console.log("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);

User Object

On successful login, you receive a User object with the following properties:
PropertyTypeDescription
uidstringUnique identifier
namestringDisplay name
avatarstringProfile picture URL
statusstringonline or offline
rolestringUser role for access control
metadataobjectCustom data
lastActiveAtnumberUnix 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());
});

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

Before calling login(), use getLoggedinUser() to check if a session exists. This prevents unnecessary API calls and potential errors.
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.
Call CometChat.logout() when users log out of your app to properly clean up the CometChat session.

Troubleshooting

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
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 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
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