Skip to main content
Quick Reference - Copy-paste ready initialization and login:
useEffect(() => {
  const initCometChat = async () => {
    const appSetting = new CometChat.AppSettingsBuilder()
      .subscribePresenceForAllUsers()
      .setRegion("REGION")
      .autoEstablishSocketConnection(true)
      .build();
    await CometChat.init("APP_ID", appSetting);
    
    // Login user (check if already logged in first)
    const loggedInUser = await CometChat.getLoggedinUser();
    if (!loggedInUser) {
      await CometChat.login("USER_UID", "AUTH_KEY");
    }
  };
  initCometChat();
}, []);
This guide demonstrates how to add chat to a React Native application using CometChat. Before you begin, we strongly recommend you read the Key Concepts guide.

I want to integrate with my app

  1. Get your Application Keys
  2. Add the CometChat Dependency
  3. Initialize CometChat
  4. Register and Login your user
  5. Integrate our UI Kits

I want to explore a sample app (includes UI)

Open the app folder in your favorite code editor and follow the steps mentioned in the README.md file.

React Native Sample App

Explore a complete React Native chat application with UI components

Get your Application Keys

Signup for CometChat and then:
1

Create a new app

Create a new application in your CometChat dashboard
2

Get your credentials

Head over to the API & Auth Keys section and note the Auth Key, App ID & Region

Add the CometChat Dependency

Install the package as an NPM module:
npm install @cometchat/chat-sdk-react-native
To integrate the CometChat React Native SDK, you need to install one more dependency.

Async-Storage

npm install @react-native-async-storage/async-storage
v2.4+ onwards, Voice & Video Calling functionality has been moved to a separate library. In case you plan to use the calling feature, please install the Calling dependency (@cometchat/calls-sdk-react-native).
npm install @cometchat/calls-sdk-react-native
The calling component requires some configuration. Please follow the steps mentioned in the Calling Component Configuration section below.

Calling Component Configuration

For @cometchat/calls-sdk-react-native, please make sure you add the following additional dependencies & permissions.

Required Dependencies

{
  "@cometchat/chat-sdk-react-native": "^4.0.18",
  "@react-native-async-storage/async-storage": "^2.2.0",
  "@react-native-community/netinfo": "^11.4.1",
  "react-native-background-timer": "^2.4.1",
  "react-native-callstats": "^3.73.22",
  "react-native-webrtc": "^124.0.6"
}

Permissions

Add the following permissions to your AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Platform-Specific Configuration

Go to the ./android folder and open the project level build.gradle file. Add all repository URLs in the repositories block under the allprojects section. Also in the same file in the buildscript section in the ext block, make sure you have set minSdkVersion to 24.Add Repository URL:
allprojects {
  repositories {
    maven {
      url "https://dl.cloudsmith.io/public/cometchat/cometchat-pro-android/maven/"
    }
  }
}
Set Minimum SDK Version:
buildscript {
  ext {
    buildToolsVersion = "29.0.2"
    minSdkVersion = 24
    compileSdkVersion = 29
    targetSdkVersion = 29
  }
}
Please update the minimum target version in the Podfile. Go to the ./ios folder and open the Podfile. In the Podfile, update the platform version to 11.0:
platform :ios, '11.0'
Open the ios/App folder and run pod install. This will create an App.xcworkspace file. Open this and run the app.

Initialize CometChat

The init() method initializes the settings required for CometChat. The init() method takes the below parameters:
ParameterDescription
appIDYour CometChat App ID
appSettingsAn object of the AppSettings class created using the AppSettingsBuilder class
The AppSettings class allows you to configure the following settings:
SettingDescription
RegionThe region where your app was created (mandatory)
Presence SubscriptionRepresents the subscription type for user presence (real-time online/offline status). See Presence Subscription
autoEstablishSocketConnection(boolean)When set to true, the SDK manages the web-socket connection internally. When set to false, you manage the connection manually. Default: true. See Managing connections manually
overrideAdminHost(adminHost: string)Uses a custom admin URL instead of the default. Used for dedicated CometChat deployments
overrideClientHost(clientHost: string)Uses a custom client URL instead of the default. Used for dedicated CometChat deployments
You need to call init() before calling any other method from CometChat. We suggest you call the init() method on app startup, preferably in the App.tsx file.
let appID = "APP_ID";
let region = "REGION";

// Build app settings with presence subscription and auto socket connection
let appSetting = new CometChat.AppSettingsBuilder()
  .subscribePresenceForAllUsers()
  .setRegion(region)
  .autoEstablishSocketConnection(true)
  .build();

// Initialize CometChat
CometChat.init(appID, appSetting).then(
  () => {
    console.log("Initialization completed successfully");
  },
  (error) => {
    console.log("Initialization failed with error:", error);
  }
);
Make sure you replace the APP_ID with your CometChat App ID and REGION with your App Region in the above code.

Register and Login your user

Once initialization is successful, you will need to create a user. To create users on the fly, you can use the createUser() method. This method takes a User object and the Auth Key as input parameters and returns the created User object if the request is successful.
let authKey = "AUTH_KEY";
let uid = "user1";
let name = "Kevin";

// Create a new user object
let user = new CometChat.User(uid);
user.setName(name);

// Register the user with CometChat
CometChat.createUser(user, authKey).then(
  (user) => {
    console.log("user created", user);
  },
  (error) => {
    console.log("error", error);
  }
);
Make sure that UID and name are specified as these are mandatory fields to create a user.
Once you have created the user successfully, you will need to log the user into CometChat using the login() method. We recommend you call the CometChat login() method once your user logs into your app. The login() method needs to be called only once.
Security Warning: This straightforward authentication method using Auth Key is ideal for proof-of-concept (POC) development or during the early stages of application development. For production environments, however, we strongly recommend using an Auth Token instead of an Auth Key to ensure enhanced security.
let UID = "cometchat-uid-1";
let authKey = "AUTH_KEY";

// Check if user is already logged in
CometChat.getLoggedinUser().then(
  (user) => {
    if (!user) {
      // Login the user if not already logged in
      CometChat.login(UID, authKey).then(
        (user) => {
          console.log("Login Successful:", { user });
        },
        (error) => {
          console.log("Login failed with exception:", { error });
        }
      );
    }
  },
  (error) => {
    console.log("Some Error Occured", { error });
  }
);
Make sure you replace the AUTH_KEY with your CometChat Auth Key in the above code.
Test Users Available: We have set up 5 users for testing with UIDs: cometchat-uid-1, cometchat-uid-2, cometchat-uid-3, cometchat-uid-4 and cometchat-uid-5.
The login() method returns the User object containing all the information of the logged-in user.
UID Format: UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed.

Integrate our UI Kits

Please refer to the React Native UI Kit section to integrate React Native UI Kit inside your app.
  • Always call init() before any other CometChat method
  • Call init() on app startup (preferably in App.tsx)
  • Use getLoggedinUser() to check login state before calling login()
  • Store user credentials securely and never expose Auth Keys in client-side code for production
  • Use Auth Token instead of Auth Key for production environments
  • Initialization fails: Verify your App ID and Region are correct
  • Login fails: Ensure the user exists or create them first using createUser()
  • Network errors: Check internet connectivity and firewall settings
  • Calling not working: Verify all calling dependencies are installed and permissions are granted
  • iOS build fails: Run pod install in the ios directory after adding dependencies

Next Steps