Azure Web PubSub Chat client library for JavaScript - version 1.0.0-beta.1

The Azure Web PubSub Chat client library enables server applications to manage chat roles, users, rooms, room membership, conversations, and messages in an Azure Web PubSub Chat hub.

Getting started

Currently supported environments

See our support policy for more details.

Prerequisites

  • An Azure subscription.
  • An existing Azure Web PubSub resource.
  • A hub name for the chat application.

Install the @azure/web-pubsub-chat package

Install the Azure WebPubSubChatService client library for JavaScript with npm:

npm install @azure/web-pubsub-chat

Create and authenticate a WebPubSubChatServiceClient

The WebPubSubChatServiceClient supports authentication with a connection string, a Microsoft Entra credential, or an AzureKeyCredential.

Authenticate with a connection string

You can find the connection string for your Azure Web PubSub resource in the Azure Portal. Because the connection string contains an access key, store it securely and do not include it in source code.

Authenticate with Microsoft Entra ID

To authenticate with Microsoft Entra ID, you will need the endpoint of your Azure Web PubSub resource and a credential. You can find the endpoint in the Azure Portal.

You can authenticate with Microsoft Entra ID using a credential from the @azure/identity library or an existing Microsoft Entra token.

To use the DefaultAzureCredential provider shown below, or other credential providers provided with the Azure SDK, please install the @azure/identity package:

npm install @azure/identity

DefaultAzureCredential supports several Microsoft Entra identities. During local development, it can use a developer identity signed in through a supported development tool. In Azure, it can use a managed identity. It can also authenticate a service principal or workload identity when configured for the environment.

Whichever identity you use must be assigned an appropriate Azure Web PubSub data-plane role. Azure resource-management roles such as Owner do not grant data-plane permissions.

Create the client with a connection string, a Microsoft Entra credential such as DefaultAzureCredential, or an AzureKeyCredential.

import { WebPubSubChatServiceClient, AzureKeyCredential } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const connectionStringClient = new WebPubSubChatServiceClient("<connectionString>", "<hubName>");
const tokenCredentialClient = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
const keyCredentialClient = new WebPubSubChatServiceClient(
  "<endpoint>",
  new AzureKeyCredential("<accessKey>"),
  "<hubName>",
);

Key concepts

WebPubSubChatServiceClient

WebPubSubChatServiceClient is the primary interface for managing chat resources in a Web PubSub hub.

Hub

A hub is the logical boundary for a chat application. Roles, users, rooms, conversations, and messages managed by a client all belong to the hub supplied to the client constructor.

Roles and permissions

A user role controls hub-level actions such as creating rooms. A room role controls actions within a room, such as publishing messages, reading message history, or inviting users.

Rooms, members, and conversations

A room contains members and has a default conversation. Add a user to a room by assigning the user a room role. Messages are published by connected chat clients and can be listed, updated, or deleted through the service client.

Entity tags

Chat resources include an etag value. Pass that value through an operation's ifMatch option to perform a conditional update or delete and prevent overwriting a newer resource version.

Examples

Set up roles, a user, and a room

Create user and room roles, create a human user and a room, and then add the user to the room.

import { WebPubSubChatServiceClient, KnownChatPermission } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
const userRoleName = "user.contoso_member";
const roomRoleName = "room.contoso_member";
const userId = "alice";
const roomId = "general";
await client.createOrReplaceRole(userRoleName, {
  permissions: [KnownChatPermission.UserCreateRoom],
});
await client.createOrReplaceRole(roomRoleName, {
  permissions: [KnownChatPermission.RoomPublishMessage, KnownChatPermission.RoomHistory],
});
await client.createOrReplaceUser(userId, {
  kind: "Human",
  nickname: "Alice",
  roleName: userRoleName,
});
const room = await client.createOrReplaceRoom(roomId, { title: "General" });
await client.createOrReplaceRoomMember(roomId, userId, { roleName: roomRoleName });
console.log(`Created room ${room.id} with conversation ${room.defaultConversation}`);

Use built-in roles and known permissions

Use BuiltInChatRoles when assigning a service-defined role and KnownChatPermission when creating a custom role. Permission strings outside the known values are also accepted for forward compatibility.

import {
  WebPubSubChatServiceClient,
  BuiltInChatRoles,
  KnownChatPermission,
} from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
await client.createOrReplaceUser("alice", {
  kind: "Human",
  nickname: "Alice",
  roleName: BuiltInChatRoles.UserNormal,
});
await client.createOrReplaceRole("room.moderator", {
  permissions: [
    KnownChatPermission.RoomHistory,
    KnownChatPermission.RoomRemoveUser,
    KnownChatPermission.RoomPublishMessage,
  ],
});

Manage roles

Create a custom role, retrieve it, list the roles in the hub, and delete the custom role when finished.

import { WebPubSubChatServiceClient, KnownChatPermission } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
const roleName = "user.contoso_member";
try {
  const role = await client.createOrReplaceRole(roleName, {
    permissions: [KnownChatPermission.UserCreateRoom, KnownChatPermission.UserFetchAllRooms],
  });
  console.log(`Created role: ${role.name}`);
  const fetchedRole = await client.getRole(roleName);
  console.log(`Fetched role: ${fetchedRole.name}`);
  for await (const listedRole of client.listRoles()) {
    console.log(`Role: ${listedRole.name}`);
  }
} finally {
  await client.deleteRole(roleName);
}

Manage a room

Create a room, retrieve its current state, and delete it.

import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
const roomId = "general";
const room = await client.createOrReplaceRoom(roomId, { title: "General" });
console.log(`Created room ${room.id} with conversation ${room.defaultConversation}`);
const fetchedRoom = await client.getRoom(roomId);
console.log(`Fetched room: ${fetchedRoom.id}, title: ${fetchedRoom.title}`);
await client.deleteRoom(roomId);

Manage a user

Create a user with a built-in role, retrieve the profile, and delete it.

import { WebPubSubChatServiceClient, BuiltInChatRoles } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
const userId = "alice";
const user = await client.createOrReplaceUser(userId, {
  kind: "Human",
  nickname: "Alice",
  roleName: BuiltInChatRoles.UserNormal,
});
console.log(`Created user: ${user.id}, nickname: ${user.nickname}`);
const fetchedUser = await client.getUser(userId);
console.log(`Fetched user: ${fetchedUser.id}, nickname: ${fetchedUser.nickname}`);
await client.deleteUser(userId);

List messages in a conversation

Use asynchronous iteration to read messages from a conversation across all result pages.

import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
for await (const message of client.listMessages("<conversationId>")) {
  console.log(`${message.createdBy}: ${message.content.text}`);
}

Generate a client access token

Generate a URL that a chat client can use to connect to the Web PubSub service as a specific user.

import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
const accessToken = await client.getClientAccessToken({ userId: "alice" });

Troubleshooting

Logging

Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the AZURE_LOG_LEVEL environment variable to info. Alternatively, logging can be enabled at runtime by calling setLogLevel in the @azure/logger:

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

For more detailed instructions on how to enable logs, you can look at the @azure/logger package docs.

Contributing

If you'd like to contribute to this library, please read the contributing guide to learn more about how to build and test the code.