/ SDKs / JavaScript
SDKs
Chat SDKs JavaScript v4
Chat SDKs JavaScript
Chat SDKs
JavaScript
Version 4

Authentication

Copy link

In order to use the features of the Chat SDK for JavaScript in your client apps, a SendbirdChat instance should be initiated in each client app through user authentication with the Sendbird server. The instance communicates and interacts with the server based on the authenticated user account and is allowed to use the Chat SDK's features. This page explains how to authenticate your user with the server.


Initialize the Chat SDK with APP_ID

Copy link

To use our chat features, you must initialize the SendbirdChat instance by passing APP_ID of your Sendbird application as an argument to a parameter in SendbirdChat.init(). The SendbirdChat.init() method must be called once across your client app. Typically, initialization is implemented in the user login view.

With the implementation of local caching, you must determine whether you would like to use local caching and configure its settings during SDK initialization. The params contains properties such as localCacheEnabled, localCacheConfig, and localCacheEncryption. First, set localCacheEnabled to true so that the SDK can use local cache for its collection instances. Then configure its database settings through localCacheConfig, which determines how much space in local cache the SDK can use and in which order it should clear cached data when the cached data reaches the limit. As for data protection, you can encrypt and decrypt cached data with a third party library of your choice and implement it during initialization. To learn more, see the Database management and Data encryption sections under Local caching.

The localCacheEnabled parameter determines whether or not the client app will use local cache through Sendbird Chat SDK. Since this is optional, the default value is set to false. If you want to build a client app with our local caching functionalities, set the localCacheEnabled parameter to true.

JavaScriptTypeScript
// Initialize the SendbirdChat instance to use APIs in your app.
const ENCRYPTION_KEY = 'encryption-key';
const sb = SendbirdChat.init({
    appId: APP_ID,
    localCacheEnabled: true,
    localCacheEncryption: {
    encrypt: (rawData) => {
            const encryptedData = CryptoJS.AES.encrypt(JSON.stringify(rawData), ENCRYPTION_KEY).toString();
            return { key: encryptedData };
    },
    decrypt: (encryptedData) => {
            const decryptedData = CryptoJS.AES.decrypt(encryptedData.key, ENCRYPTION_KEY).toString(CryptoJS.enc.Utf8);
            return JSON.parse(decryptedData);
        },
    },
    localCacheConfig: new LocalCacheConfig({
        maxSize: 256,           // The value is in MB.
        clearOrder: CachedDataClearOrder.MESSAGE_COLLECTION_ACCESSED_AT,
    }),
    customApiHost: API_HOST,
    customWebSocketHost: WS_HOST,
    logLevel: LogLevel.WARNING,
    modules: [
        new GroupChannelModule(),
    ],
});

When localCacheEnabled is set to true, different data stores are utilized depending on the app environment. It employs indexedDB in a browser environment while using MMKV in a React Native environment. For those who are using local caching in React Native, put useMMKVStorageStore to the SendbirdChat.init() method as a parameter to set MMKV as the database storage.

JavaScriptTypeScript
import { MMKV } from 'react-native-mmkv';

const params = {
  appId: APP_ID,
  localCacheEnabled: true,
  useMMKVStorageStore: new MMKV(),
};
var sb = SendbirdChat.init(params);

Note: If indexedDBstore isn't available in the browser, the Chat SDK will fall back to use the device's memory, not the local cache, even if localCacheEnabled is set to true. When this happens, a warning will show in the logger to notify the situation.

Understanding modules

Copy link

With the launch of Chat SDK v4.0.0., modules have been introduced to Sendbird Chat SDK to reduce the page loading time and allow users to choose Chat features they would like to import. You can import the @sendbird/chat package first, which adds SendbirdChat and MessageModule. Depending on which chat features you would like to use, you can provide GroupChannelModule or OpenChannelModule from the @sendbird/chat/groupChannel and @sendbird/chat/openChannel packages respectively as a parameter of the SendbirdChat.init() method. You can also set them in SendbirdChatParams and pass it to the init() method.

JavaScriptTypeScript
import SendbirdChat from '@sendbird/chat';
import { GroupChannelModule, SendbirdGroupChat } from '@sendbird/chat/groupChannel';

const params = {
    appId: APP_ID,
    modules: [
        new GroupChannelModule(),
    ],
};
const sb = SendbirdChat.init(params);

With TypeScript, each module provides a wrapper type of the SendbirdChat instance which allows the module to access GroupChannelModule and OpenChannelModule with sb.groupChannel or sb.openChannel respectively. You can cast the SendbirdChat instance to SendbirdGroupChat or SendbirdOpenChat to access the modules.

JavaScriptTypeScript
const params = {
    appId: APP_ID,
    modules: [
        new GroupChannelModule(),
    ],
};
const sb = SendbirdChat.init(params);

// Only the SendbirdGroupChat type provides a groupChannel module interface.
await sb.groupChannel.createChannel(params);

// MessageModule is built into the SendbirdChat instance on init() so it could be accessed without casting.
await sb.message.getMessage(messageId);

Connect to the Sendbird server with a user ID

Copy link

By default, the Sendbird server can authenticate a user with just a unique user ID. Then, the server queries the database to check for a match upon connection request. If no matching user ID is found, the server creates a new user account with the user ID. The ID should be unique within a Sendbird application to be distinguishable from other identifiers such as a hashed email address or a phone number in your service.

While authenticating with just the user ID is convenient in the developing and testing stages of a service, a more secure authentication process using tokens is strongly recommended for most production environments.

If you are using local caching, the connection process will differ depending on the callback. When one of the error codes 400300, 400301, 400302, and 400310 returns, you should clear all user data cached in the local storage and then reconnect to the Sendbird server. Except when these errors occur, the client app can still draw a channel list view and a chat view in the offline mode using locally cached data. The SDK will receive a user object through a callback and try to reconnect later on.

Note: The user object can be passed in a callback only when the client app has succeeded in making the connection with the same user ID in the past. Since the sb.connect() method now requires a callback, use sb.currentUser to fetch the user data. Go to the event handler page to learn more about the usages of the Chat SDK's handlers and callbacks.

JavaScriptTypeScript
const user = await sb.connect(USER_ID);

For Chat SDKs that don't use local caching, the connection process remains the same. When an error occurs, the SDK must attempt to reconnect again.

Note: Apart from initializing the SendbirdChat instance, you should connect to the Sendbird server before calling almost every method through the Chat SDK. If you attempt to call a method without connecting, a CONNECTION_REQUIRED (800101) error would be returned.


Manage connections with the Sendbird server

Copy link

Unlike the Chat SDKs for iOS and Android, the Chat SDK for JavaScript doesn't manage connections to the Sendbird server when the foreground and background states of your web app changes on different types of devices. In this situation, you should call the connect() or disconnect() methods explicitly depending on how you implement your use cases.

One user ID can make connections to up to 30 devices or browsers simultaneously. All connections from the single user ID are counted and reflected in your application’s concurrent connection number, which is used to calculate your service billing.


Connect to the Sendbird server with a user ID and a token

Copy link

For a more secure way of authenticating a user, you can require an authentication token, which can be an access token or a session token, in addition to a unique user ID. Any token issued for a user must be provided to the Sendbird server each time the user logs in by passing the token as an argument to the authToken parameter of the sb.connect() method.

Using an access token

Copy link

Through our Chat Platform API, an access token can be generated when creating a user. You can also issue an access token for an existing user. Once an access token is issued, a user is required to provide the access token in the sb.connect() method which is used for logging in.

  1. Using the Chat API, create a Sendbird user account with information submitted when a user signs up or log in to your service.

  2. Save the user ID along with the issued access token to your persistent storage which is securely managed.

  3. When the user attempts to log in to a client app, load the user ID and access token from the storage, and then pass them to the sb.connect() method.

  4. Periodically replacing the user's access token is recommended to protect the account.

Note: From Settings > Application > Security > Access token permission setting on your dashboard, you're able to prevent users without an access token from logging in to your Sendbird application or restrict their access to read and write messages.

JavaScriptTypeScript
const user = await sb.connect(USER_ID, ACCESS_TOKEN);

Using a session token

Copy link

You can also use a session token instead of an access token to authenticate a user. Session tokens are a more secure option because they expire after a certain period whereas access tokens don't. See Chat Platform API guides for further explanation about the difference between access token and session token, how to issue a session token, and how to revoke all session tokens.


Set a session handler

Copy link

When a user logs in to a client app using the Chat SDK, a user can be authenticated with a session token. If a user is authenticated with a session token, the Chat SDK connects the user to the Sendbird server and can send data requests to it for ten minutes as long as the session token hasn't expired or hasn't been revoked.

Upon the user's session expiration, the Chat SDK will refresh the session internally. However, if the session token has expired or has been revoked, the Chat SDK can't do so. In that case, the client app needs to implement a SessionHandler instance to refresh the token and pass it back to the SDK so that it can refresh the session again.

Note: A SessionHandler instance must be set before the server connection is requested.

The following code shows how to implement the handler.

JavaScriptTypeScript
const sessionHandler = new SessionHandler();
sessionHandler.onSessionTokenRequired = (resolve, reject) => {
    // A new session token is required in the SDK to refresh the session.
    // Refresh the session token and pass it onto the SDK through resolve(NEW_TOKEN).
    // If you don't want to refresh the session, pass on a null value through resolve(null).
    // If any error occurs while refreshing the token, let the SDK know about it through reject(error).

};
sessionHandler.onSessionClosed = () => {
    // The session refresh has been denied from the app.
    // The client app should guide the user to a login page to log in again.
};
sessionHandler.onSessionRefreshed = () => {
    // OPTIONAL. No action is required.
    // This is called when the session is refreshed.
};
sessionHandler.onSessionError = (err) => {
    // OPTIONAL. No action is required.
    // This is called when an error occurs during the session refresh.
};
sb.setSessionHandler(sessionHandler);

When the SessionHandler.onSessionTokenRequired() is invoked, the SDK waits for a specific amount of time to receive a new session token from the client app.

If neither resolve() nor reject() are called within the specified timeout period, the socket connection will be disconnected. If this occurs, the client app has to manually call sb.connect(USER_ID, AUTH_TOKEN) for a new socket connection.

The timeout period can be set using the sessionTokenRefreshTimeout method as shown in the code below.

JavaScriptTypeScript
sb.options.sessionTokenRefreshTimeout = 60; // sec

Disconnect from the Sendbird server

Copy link

Disconnect a user from the Sendbird server when they no longer need to receive messages from an online state. However, the user will still receive push notifications for new messages from group channels they've joined.

When a client app is disconnected, all event handlers registered through sb.groupChannel.addGroupChannelHandler(), sb.openChannel.addOpenChannelHandler, or sb.addConnectionHandler() stop receiving event callbacks from the server. Then, all internally cached data in the client app are flushed. This includes channels that are cached when sb.openChannel.getChannel() or sb.groupChannel.getChannel() is called, as well as locally cached channels and messages.

JavaScriptTypeScript
await sb.disconnect();

Disconnect the WebSocket only

Copy link

While calling SendbirdChat.disconnect() disconnects the WebSocket as well as clear local cache data, you can call SendbirdChat.disconnectWebSocket to disconnect the WebSocket only and keep the locally cached data.

TypeScriptJavaScript
await sb.disconnectWebSocket();

To reconnect after calling disconnectWebSocket, use the SendbirdChat.connect() method as shown in the code below.

TypeScriptJavaScript
try {
  const user:User = await sb.connect(userId);
} catch {
  // error handle
}