Chat SDK for JavaScript

The Azure Communication Services (ACS) Chat SDK for JavaScript enables you to add rich, real-time chat experiences to your web applications. Leverage the power of Azure's global infrastructure to build scalable, reliable, and engaging communication features.

This documentation provides a comprehensive guide to using the JavaScript Chat SDK, covering everything from initial setup to advanced features.

Getting Started

To begin using the Chat SDK, you'll need to install it via npm or yarn.

npm install @azure/communication-chat --save

Alternatively, you can use yarn:

yarn add @azure/communication-chat

Next, you'll need to create an instance of the ChatClient. This typically involves obtaining an access token and your Azure Communication Services resource endpoint.

Core Concepts

ChatClient

The ChatClient is the primary entry point for interacting with the Chat service. It allows you to manage chat threads, participants, and messages.

Instantiate ChatClient

Requires your Communication Services endpoint and an authenticated credential (e.g., an access token).


import { ChatClient } from "@azure/communication-chat";
import { AzureKeyCredential } from "@azure/core-auth";

// Replace with your actual endpoint and token
const endpoint = "https://your-resource.communication.azure.com";
const token = "YOUR_ACCESS_TOKEN";

const credential = new AzureKeyCredential(token);
const chatClient = new ChatClient(endpoint, credential);
                        

ChatThreadClient

Represents a specific chat thread. You obtain a ChatThreadClient from the ChatClient using a thread ID.

Get ChatThreadClient

Use the thread ID to get a client for that specific thread.


const threadId = "YOUR_THREAD_ID";
const threadClient = chatClient.getChatThreadClient(threadId);
                        

ChatMessage

Represents a single message within a chat thread. It contains sender information, content, and metadata.

User Identity

Users in the chat system are identified by unique string identifiers. These can be Azure Active Directory Object IDs, Microsoft Accounts, or custom identifiers.

Usage Examples

Create a Chat Thread

Create a new chat thread with specified participants.


async function createChatThreadExample() {
    const threadOptions = {
        topic: "Project Discussion"
    };
    const participantIds = [
        { id: "user1_id" },
        { id: "user2_id" }
    ];

    try {
        const createThreadResult = await chatClient.createChatThread(participantIds, threadOptions);
        console.log(`Chat thread created with ID: ${createThreadResult.chatThread.id}`);
        return createThreadResult.chatThread.id;
    } catch (error) {
        console.error("Error creating chat thread:", error);
        throw error;
    }
}
                        

Send a Message

Send a text message to an existing chat thread.


async function sendMessageExample(threadClient, messageContent) {
    try {
        const sendResult = await threadClient.sendMessage({ content: messageContent });
        console.log(`Message sent with ID: ${sendResult.id}`);
        return sendResult.id;
    } catch (error) {
        console.error("Error sending message:", error);
        throw error;
    }
}
                        

Receive Messages

Subscribe to real-time events to receive new messages as they arrive.


function subscribeToMessagesExample(threadClient) {
    const messageCallback = (event) => {
        console.log(`New message received:`);
        console.log(`  From: ${event.from}`);
        console.log(`  Content: ${event.content}`);
        console.log(`  Timestamp: ${event.receivedTimestamp}`);
    };

    const subscription = threadClient.on("chatMessageReceived", messageCallback);
    console.log("Subscribed to new messages.");

    // To unsubscribe later:
    // subscription.unsubscribe();
}
                        

Add Participant

Invite a new user to join an existing chat thread.


async function addParticipantExample(threadClient, userId) {
    const participant = {
        id: userId,
        // Optional: Add display name and metadata
        // displayName: "New User",
        // metadata: { "key": "value" }
    };
    try {
        await threadClient.addParticipant(participant);
        console.log(`Participant ${userId} added to the thread.`);
    } catch (error) {
        console.error(`Error adding participant ${userId}:`, error);
        throw error;
    }
}
                        

Remove Participant

Remove a participant from a chat thread.


async function removeParticipantExample(threadClient, userId) {
    try {
        await threadClient.removeParticipant(userId);
        console.log(`Participant ${userId} removed from the thread.`);
    } catch (error) {
        console.error(`Error removing participant ${userId}:`, error);
        throw error;
    }
}
                        

API Reference

For a detailed breakdown of all available methods, properties, and types within the Chat SDK, please refer to the official API reference documentation.

Azure Communication Services Chat SDK API Reference

Troubleshooting

Common issues and their resolutions:

  • Authentication Errors: Ensure your access token is valid and has the necessary permissions. Tokens expire, so implement a refresh mechanism.
  • Network Issues: Verify your network connection and that your firewall rules allow access to Azure Communication Services endpoints.
  • Event Handling: Make sure you are properly subscribing to events and handling potential errors during event callbacks.
  • Rate Limiting: Be aware of API rate limits and implement retry logic with exponential backoff for requests that fail due to throttling.

For more advanced troubleshooting, consult the Azure Communication Services Troubleshooting Guide.