Overview
This guide demonstrates how to add chat to a Javascript application using CometChat. Before you begin, we strongly recommend you read the Key Concepts guide.
I want to integrate with my app
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.
Get your Application Keys
Signup for CometChat and then:
- Create a new app
- Head over to the API & Auth Keys section and note the Auth Key, App ID & Region
Add the CometChat Dependency
NPM
- Javascript
npm install @cometchat/chat-sdk-javascript@latest --save
Then, import the CometChat
object wherever you want to use CometChat.
- Javascript
import { CometChat } from "@cometchat/chat-sdk-javascript";
HTML (via CDN)
Include the CometChat Javascript library in your HTML code
- HTML
<script
type="text/javascript"
src="https://unpkg.com/@cometchat/chat-sdk-javascript@latest/CometChat.js"
></script>
Server Side Rendering (SSR) Compatibility
You can use CometChat with SSR frameworks such as Next.js or NuxtJS by importing it dynamically on the client side.
Next.js
You need to import the CometChat SDK dynamically in the useEffect
React Hook or componentDidMount()
lifecycle method.
- Home.js(Functional)
- Home.js(Class Component)
- Chat.js
- const.js
import React from "react";
import Chat from "./Chat";
export default function Home() {
let [libraryImported, setLibraryImported] = React.useState(false);
React.useEffect(() => {
window.CometChat = require("@cometchat/chat-sdk-javascript").CometChat;
setLibraryImported(true);
});
return libraryImported ? <Chat /> : <p>Loading....</p>;
}
import React from 'react';
import Chat from './Chat';
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
libraryImported: false
};
}
componentDidMount(){
CometChat = require("@cometchat/chat-sdk-javascript").CometChat;
this.setState({libraryImported: true});
}
return(
this.state.libraryImported ? <Chat/> : <p>Loading....</p>
)
}
import React, { Component } from "react";
import { COMETCHAT_CONSTANTS } from "./CONSTS";
export default class Chat extends Component {
constructor(props) {
super(props);
this.state = {
user: undefined,
};
}
componentDidMount() {
this.init();
}
init() {
CometChat.init(
COMETCHAT_CONSTANTS.APP_ID,
new CometChat.AppSettingsBuilder()
.setRegion(COMETCHAT_CONSTANTS.REGION)
.subscribePresenceForAllUsers()
.build()
).then(
() => {
this.login();
},
(error) => {
console.log("Init failed with exception:", error);
}
);
}
login() {
let UID = "UID";
CometChat.login(UID, COMETCHAT_CONSTANTS.AUTH_KEY).then(
(user) => {
this.setState({ user });
},
(error) => {
console.log("Login failed with exception:", error);
}
);
}
render() {
return this.state.user ? (
<div>User logged in</div>
) : (
<div>User not logged in</div>
);
}
}
export const COMETCHAT_CONSTANTS = {
APP_ID: "APP_ID",
REGION: "REGION",
AUTH_KEY: "AUTH_KEY",
};
NuxtJS
You need to import the CometChat SDK dynamically in the mounted
lifecycle hook.
- index.vue
- chat.vue
- CONST.js
<template>
<div v-if="libraryImported">
<chat/>
</div>
<div v-else>Loading....</div>
</template>
<script>
export default {
name: "Index",
components: {
'chat': () => import('./chat')
},
data() {
return{
libraryImported: false
}
},
mounted() {
window.CometChat = require('@cometchat/chat-sdk-javascript').CometChat;
this.libraryImported = true;
}
}
</script>
<template>
<div v-if="user"> User logged in </div>
<div v-else> User not logged in </div>
</template>
<script>
import CONSTS from './CONSTS';
export default {
name: "chat",
data() {
return{
user: null
}
},
mounted() {
CometChat.init(CONSTS.APP_ID, new CometChat.AppSettingsBuilder().setRegion(CONSTS.REGION).subscribePresenceForAllUsers().build()).then(
() => {
let UID = "UID";
CometChat.login(UID, CONSTS.AUTH_KEY).then(
user => {
this.user = user;
}, error => {
console.log("Login failed with exception:", error);
}
);
}, error => {
console.log("error in init", error);
}
);
}
}
</script>
module.exports = {
APP_ID: "APP_ID",
REGION: "REGION",
AUTH_KEY: "AUTH_KEY",
};
Initialize CometChat
The init()
method initializes the settings required for CometChat. The init()
method takes the below parameters:
- appID - Your CometChat App ID
- appSettings - An object of the AppSettings class can be created using the AppSettingsBuilder class. The region field is mandatory and can be set using the
setRegion()
method.
The AppSettings
class allows you to configure two settings:
- Region: The region where your app was created.
- Presence Subscription: Represents the subscription type for user presence (real-time online/offline status)
- autoEstablishSocketConnection(boolean value): This property takes a boolean value which when set to
true
informs the SDK to manage the web-socket connection internally. If set tofalse
, it informs the SDK that the web-socket connection will be managed manually. The default value for this parameter is true. For more information on this, please check the Managing Web-Socket connections manually section. The default value for this property is true. - overrideAdminHost(adminHost: string): This method takes the admin URL as input and uses this admin URL instead of the default admin URL. This can be used in case of dedicated deployment of CometChat.
- overrideClientHost(clientHost: string): This method takes the client URL as input and uses this client URL instead of the default client URL. This can be used in case of dedicated deployment of CometChat.
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 index.js
file.
- Javascript
- Typescript
let appID = "APP_ID";
let region = "APP_REGION";
let appSetting = new CometChat.AppSettingsBuilder()
.subscribePresenceForAllUsers()
.setRegion(region)
.autoEstablishSocketConnection(true)
.build();
CometChat.init(appID, appSetting).then(
() => {
console.log("Initialization completed successfully");
},
(error) => {
console.log("Initialization failed with error:", error);
}
);
let appID: string = "APP_ID",
region: string = "APP_REGION",
appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder()
.subscribePresenceForAllUsers()
.setRegion(region)
.autoEstablishSocketConnection(true)
.build();
CometChat.init(appID, appSetting).then(
(initialized: boolean) => {
console.log("Initialization completed successfully", initialized);
}, (error: CometChat.CometChatException) => {
console.log("Initialization failed with error:", error);
}
);
Make sure you replace the APP_ID
with your CometChat App ID and APP_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.
- Javascript
- typescript
let authKey = "AUTH_KEY";
var UID = "user1";
var name = "Kevin";
var user = new CometChat.User(UID);
user.setName(name);
CometChat.createUser(user, authKey).then(
(user) => {
console.log("user created", user);
},
(error) => {
console.log("error", error);
}
);
let authKey: string = "AUTH_KEY",
UID: string = "user1",
name: string = "Kevin";
var user = new CometChat.User(UID);
user.setName(name);
CometChat.createUser(user, authKey).then(
(user: CometChat.User) => {
console.log("user created", user);
},
(error: CometChat.CometChatException) => {
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.
This straightforward authentication method 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.
- javascript
- typescript
var UID = "SUPERHERO1";
var authKey = "AUTH_KEY";
CometChat.getLoggedinUser().then(
(user) => {
if (!user) {
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 });
}
);
var UID: string = "SUPERHERO1",
authKey: string = "AUTH_KEY";
CometChat.getLoggedinUser().then(
(user: CometChat.User) => {
if (!user) {
CometChat.login(UID, authKey).then(
(user: CometChat.User) => {
console.log("Login Successful:", { user });
},
(error: CometChat.CometChatException) => {
console.log("Login failed with exception:", { error });
}
);
}
},
(error: CometChat.CometChatException) => {
console.log("Some Error Occured", { error });
}
);
Make sure you replace the AUTH_KEY
with your CometChat AuthKey in the above code.
We have set up 5 users for testing having UIDs: SUPERHERO1
, SUPERHERO2
, SUPERHERO3
, SUPERHERO4
and SUPERHERO5
.
The login()
method returns the User
object on Promise
resolved containing all the information of the logged-in user.
UID can be alphanumeric with an underscore and hyphen. Spaces, punctuation and other special characters are not allowed.
Integrate our UI Kits
- Please refer to the section to integrate React UI Kit into your website.
- Please refer to the section to integrate Angular UI Kit into your website.
- Please refer to the section to integrate Vue UI Kit into your website.
Integrate our Chat Widget
- Please refer to the section to integrate Chat Widget into your Website.