オプション
家 Skill API開発 azure-web-pubsub-ts

azure-web-pubsub-ts

microsoft/skills microsoft/skills

Azure Web PubSub SDK for JavaScript を使用して、サーバー側の管理、クライアント側のパブリッシュ/サブスクライブ、Express イベントハンドラーを含むリアルタイムメッセージングアプリケーションを構築します。

...すべて拡張します
1
更新された時間 2026年9月13日

TypeScript 用の Azure Web PubSub SDK

WebSocket 接続およびパブリッシュ/サブスクライブパターンを用いたリアルタイムメッセージング。

インストール

# サーバー側の管理
npm install @azure/web-pubsub @azure/identity

# クライアント側のリアルタイムメッセージング
npm install @azure/web-pubsub-client

# イベントハンドラー用の Express ミドルウェア
npm install @azure/web-pubsub-express

環境変数

WEBPUBSUB_CONNECTION_STRING=Endpoint=https://<resource>.webpubsub.azure.com;AccessKey=<key>;Version=1.0;
WEBPUBSUB_ENDPOINT=https://<resource>.webpubsub.azure.com
AZURE_TOKEN_CREDENTIALS=prod # 本番環境で DefaultAzureCredential を使用する場合にのみ必要
</resource></key></resource>

サーバー側: WebPubSubServiceClient

認証

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

// ローカル開発: DefaultAzureCredential。本番環境: AZURE_TOKEN_CREDENTIALS=prod または AZURE_TOKEN_CREDENTIALS=<特定の資格情報> を設定
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// または、本番環境で特定の資格情報を直接使用:
// 詳細は https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest#credential-classes を参照
// const credential = new ManagedIdentityCredential();

// 接続文字列
const client = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_CONNECTION_STRING!,
  "chat"  // ハブ名
);

// Microsoft Entra 資格情報 (推奨)
const client2 = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_ENDPOINT!,
  credential,
  "chat"
);

// AzureKeyCredential
const client3 = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_ENDPOINT!,
  new AzureKeyCredential("<access-key>"),
  "chat"
);
</access-key></specific_credential>

クライアントアクセストークンの生成

// 基本トークン
const token = await client.getClientAccessToken();
console.log(token.url);  // wss://...?access_token=...

// ユーザー ID を含むトークン
const userToken = await client.getClientAccessToken({
  userId: "user123",
});

// 権限を含むトークン
const permToken = await client.getClientAccessToken({
  userId: "user123",
  roles: [
    "webpubsub.joinLeaveGroup",
    "webpubsub.sendToGroup",
    "webpubsub.sendToGroup.chat-room",  // 特定のグループ
  ],
  groups: ["chat-room"],  // 接続時に自動参加
  expirationTimeInMinutes: 60,
});

メッセージの送信

// ハブ内のすべての接続にブロードキャスト
await client.sendToAll({ message: "こんにちは、みんな!" });
await client.sendToAll("プレーンテキスト", { contentType: "text/plain" });

// 特定のユーザーに送信(そのユーザーのすべての接続)
await client.sendToUser("user123", { message: "こんにちは!" });

// 特定の接続に送信
await client.sendToConnection("connectionId", { data: "ダイレクトメッセージ" });

// フィルター付き送信(OData 構文)
await client.sendToAll({ message: "フィルター済み" }, {
  filter: "userId ne 'admin'",
});

グループ管理

const group = client.group("chat-room");

// ユーザー/接続をグループに追加
await group.addUser("user123");
await group.addConnection("connectionId");

// グループから削除
await group.removeUser("user123");

// グループに送信
await group.sendToAll({ message: "グループメッセージ" });

// グループ内のすべての接続を閉じる
await group.closeAllConnections({ reason: "メンテナンス" });

接続管理

// 存在確認
const userExists = await client.userExists("user123");
const connExists = await client.connectionExists("connectionId");

// 接続を閉じる
await client.closeConnection("connectionId", { reason: "キック" });
await client.closeUserConnections("user123");
await client.closeAllConnections();

// 権限
await client.grantPermission("connectionId", "sendToGroup", { targetName: "chat" });
await client.revokePermission("connectionId", "sendToGroup", { targetName: "chat" });

クライアント側: WebPubSubClient

接続

import { WebPubSubClient } from "@azure/web-pubsub-client";

// 直接 URL
const client = new WebPubSubClient("<client-access-url>");

// negotiate エンドポイントから動的 URL
const client2 = new WebPubSubClient({
  getClientAccessUrl: async () => {
    const response = await fetch("/negotiate");
    const { url } = await response.json();
    return url;
  },
});

// 開始前にハンドラーを登録
client.on("connected", (e) => {
  console.log(`接続済み: ${e.connectionId}`);
});

client.on("group-message", (e) => {
  console.log(`${e.message.group}: ${e.message.data}`);
});

await client.start();
</client-access-url>

メッセージの送信

// まずグループに参加
await client.joinGroup("chat-room");

// グループに送信
await client.sendToGroup("chat-room", "こんにちは!", "text");
await client.sendToGroup("chat-room", { type: "message", content: "やあ" }, "json");

// 送信オプション
await client.sendToGroup("chat-room", "こんにちは", "text", {
  noEcho: true,        // 送信者へのエコーバックをしない
  fireAndForget: true, // ACK を待たない
});

// サーバーにイベントを送信
await client.sendEvent("userAction", { action: "typing" }, "json");

イベントハンドラー

// 接続のライフサイクル
client.on("connected", (e) => {
  console.log(`接続済み: ${e.connectionId}, ユーザー: ${e.userId}`);
});

client.on("disconnected", (e) => {
  console.log(`切断済み: ${e.message}`);
});

client.on("stopped", () => {
  console.log("クライアントが停止しました");
});

// メッセージ
client.on("group-message", (e) => {
  console.log(`[${e.message.group}] ${e.message.fromUserId}: ${e.message.data}`);
});

client.on("server-message", (e) => {
  console.log(`サーバー: ${e.message.data}`);
});

// 再接続失敗
client.on("rejoin-group-failed", (e) => {
  console.log(`${e.group} への再参加に失敗: ${e.error}`);
});

Express イベントハンドラー

import express from "express";
import { WebPubSubEventHandler } from "@azure/web-pubsub-express";

const app = express();

const handler = new WebPubSubEventHandler("chat", {
  path: "/api/webpubsub/hubs/chat/",

  // ブロッキング: 接続の承認/拒否
  handleConnect: (req, res) => {
    if (!req.claims?.sub) {
      res.fail(401, "認証が必要です");
      return;
    }
    res.success({
      userId: req.claims.sub[0],
      groups: ["general"],
      roles: ["webpubsub.sendToGroup"],
    });
  },

  // ブロッキング: カスタムイベントの処理
  handleUserEvent: (req, res) => {
    console.log(`${req.context.userId} からのイベント:`, req.data);
    res.success(`受信: ${req.data}`, "text");
  },

  // ノンブロッキング
  onConnected: (req) => {
    console.log(`クライアント接続: ${req.context.connectionId}`);
  },

  onDisconnected: (req) => {
    console.log(`クライアント切断: ${req.context.connectionId}`);
  },
});

app.use(handler.getMiddleware());

// negotiate エンドポイント
app.get("/negotiate", async (req, res) => {
  const token = await serviceClient.getClientAccessToken({
    userId: req.user?.id,
  });
  res.json({ url: token.url });
});

app.listen(8080);

主要な型

// サーバー
import {
  WebPubSubServiceClient,
  WebPubSubGroup,
  GenerateClientTokenOptions,
  HubSendToAllOptions,
} from "@azure/web-pubsub";

// クライアント
import {
  WebPubSubClient,
  WebPubSubClientOptions,
  OnConnectedArgs,
  OnGroupDataMessageArgs,
} from "@azure/web-pubsub-client";

// Express
import {
  WebPubSubEventHandler,
  ConnectRequest,
  UserEventRequest,
  ConnectResponseHandler,
} from "@azure/web-pubsub-express";

ベストプラクティス

  1. Microsoft Entra 資格情報を使用する - ローカル開発では DefaultAzureCredential を使用し、本番環境では ManagedIdentityCredential または WorkloadIdentityCredential を使用する
  2. 開始前にハンドラーを登録する - 初期イベントを見逃さないようにする
  3. チャネルとしてグループを使用する - トピックやルームごとにメッセージを整理する
  4. 再接続を処理する - クライアントはデフォルトで自動再接続する
  5. handleConnect で検証する - 認可されていない接続は早期に拒否する
  6. noEcho を使用する - 必要に応じてメッセージの送信者へのエコーバックを防ぐ
GitHubで見る
---
name: azure-web-pubsub-ts
description: Build real-time messaging applications using Azure Web PubSub SDKs for JavaScript, including server-side management, client-side pub/sub, and Express event handlers.
license: MIT
---

# Azure Web PubSub SDKs for TypeScript

Real-time messaging with WebSocket connections and pub/sub patterns.

## Installation

```bash
# Server-side management
npm install @azure/web-pubsub @azure/identity

# Client-side real-time messaging
npm install @azure/web-pubsub-client

# Express middleware for event handlers
npm install @azure/web-pubsub-express
```

## Environment Variables

```bash
WEBPUBSUB_CONNECTION_STRING=Endpoint=https://<resource>.webpubsub.azure.com;AccessKey=<key>;Version=1.0;
WEBPUBSUB_ENDPOINT=https://<resource>.webpubsub.azure.com
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```

## Server-Side: WebPubSubServiceClient

### Authentication

```typescript
import { WebPubSubServiceClient, AzureKeyCredential } from "@azure/web-pubsub";
import { DefaultAzureCredential, ManagedIdentityCredential } from "@azure/identity";

// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest#credential-classes
// const credential = new ManagedIdentityCredential();

// Connection string
const client = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_CONNECTION_STRING!,
  "chat"  // hub name
);

// Microsoft Entra Token Credential (recommended)
const client2 = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_ENDPOINT!,
  credential,
  "chat"
);

// AzureKeyCredential
const client3 = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_ENDPOINT!,
  new AzureKeyCredential("<access-key>"),
  "chat"
);
```

### Generate Client Access Token

```typescript
// Basic token
const token = await client.getClientAccessToken();
console.log(token.url);  // wss://...?access_token=...

// Token with user ID
const userToken = await client.getClientAccessToken({
  userId: "user123",
});

// Token with permissions
const permToken = await client.getClientAccessToken({
  userId: "user123",
  roles: [
    "webpubsub.joinLeaveGroup",
    "webpubsub.sendToGroup",
    "webpubsub.sendToGroup.chat-room",  // specific group
  ],
  groups: ["chat-room"],  // auto-join on connect
  expirationTimeInMinutes: 60,
});
```

### Send Messages

```typescript
// Broadcast to all connections in hub
await client.sendToAll({ message: "Hello everyone!" });
await client.sendToAll("Plain text", { contentType: "text/plain" });

// Send to specific user (all their connections)
await client.sendToUser("user123", { message: "Hello!" });

// Send to specific connection
await client.sendToConnection("connectionId", { data: "Direct message" });

// Send with filter (OData syntax)
await client.sendToAll({ message: "Filtered" }, {
  filter: "userId ne 'admin'",
});
```

### Group Management

```typescript
const group = client.group("chat-room");

// Add user/connection to group
await group.addUser("user123");
await group.addConnection("connectionId");

// Remove from group
await group.removeUser("user123");

// Send to group
await group.sendToAll({ message: "Group message" });

// Close all connections in group
await group.closeAllConnections({ reason: "Maintenance" });
```

### Connection Management

```typescript
// Check existence
const userExists = await client.userExists("user123");
const connExists = await client.connectionExists("connectionId");

// Close connections
await client.closeConnection("connectionId", { reason: "Kicked" });
await client.closeUserConnections("user123");
await client.closeAllConnections();

// Permissions
await client.grantPermission("connectionId", "sendToGroup", { targetName: "chat" });
await client.revokePermission("connectionId", "sendToGroup", { targetName: "chat" });
```

## Client-Side: WebPubSubClient

### Connect

```typescript
import { WebPubSubClient } from "@azure/web-pubsub-client";

// Direct URL
const client = new WebPubSubClient("<client-access-url>");

// Dynamic URL from negotiate endpoint
const client2 = new WebPubSubClient({
  getClientAccessUrl: async () => {
    const response = await fetch("/negotiate");
    const { url } = await response.json();
    return url;
  },
});

// Register handlers BEFORE starting
client.on("connected", (e) => {
  console.log(`Connected: ${e.connectionId}`);
});

client.on("group-message", (e) => {
  console.log(`${e.message.group}: ${e.message.data}`);
});

await client.start();
```

### Send Messages

```typescript
// Join group first
await client.joinGroup("chat-room");

// Send to group
await client.sendToGroup("chat-room", "Hello!", "text");
await client.sendToGroup("chat-room", { type: "message", content: "Hi" }, "json");

// Send options
await client.sendToGroup("chat-room", "Hello", "text", {
  noEcho: true,        // Don't echo back to sender
  fireAndForget: true, // Don't wait for ack
});

// Send event to server
await client.sendEvent("userAction", { action: "typing" }, "json");
```

### Event Handlers

```typescript
// Connection lifecycle
client.on("connected", (e) => {
  console.log(`Connected: ${e.connectionId}, User: ${e.userId}`);
});

client.on("disconnected", (e) => {
  console.log(`Disconnected: ${e.message}`);
});

client.on("stopped", () => {
  console.log("Client stopped");
});

// Messages
client.on("group-message", (e) => {
  console.log(`[${e.message.group}] ${e.message.fromUserId}: ${e.message.data}`);
});

client.on("server-message", (e) => {
  console.log(`Server: ${e.message.data}`);
});

// Rejoin failure
client.on("rejoin-group-failed", (e) => {
  console.log(`Failed to rejoin ${e.group}: ${e.error}`);
});
```

## Express Event Handler

```typescript
import express from "express";
import { WebPubSubEventHandler } from "@azure/web-pubsub-express";

const app = express();

const handler = new WebPubSubEventHandler("chat", {
  path: "/api/webpubsub/hubs/chat/",
  
  // Blocking: approve/reject connection
  handleConnect: (req, res) => {
    if (!req.claims?.sub) {
      res.fail(401, "Authentication required");
      return;
    }
    res.success({
      userId: req.claims.sub[0],
      groups: ["general"],
      roles: ["webpubsub.sendToGroup"],
    });
  },
  
  // Blocking: handle custom events
  handleUserEvent: (req, res) => {
    console.log(`Event from ${req.context.userId}:`, req.data);
    res.success(`Received: ${req.data}`, "text");
  },
  
  // Non-blocking
  onConnected: (req) => {
    console.log(`Client connected: ${req.context.connectionId}`);
  },
  
  onDisconnected: (req) => {
    console.log(`Client disconnected: ${req.context.connectionId}`);
  },
});

app.use(handler.getMiddleware());

// Negotiate endpoint
app.get("/negotiate", async (req, res) => {
  const token = await serviceClient.getClientAccessToken({
    userId: req.user?.id,
  });
  res.json({ url: token.url });
});

app.listen(8080);
```

## Key Types

```typescript
// Server
import {
  WebPubSubServiceClient,
  WebPubSubGroup,
  GenerateClientTokenOptions,
  HubSendToAllOptions,
} from "@azure/web-pubsub";

// Client
import {
  WebPubSubClient,
  WebPubSubClientOptions,
  OnConnectedArgs,
  OnGroupDataMessageArgs,
} from "@azure/web-pubsub-client";

// Express
import {
  WebPubSubEventHandler,
  ConnectRequest,
  UserEventRequest,
  ConnectResponseHandler,
} from "@azure/web-pubsub-express";
```

## Best Practices

1. **Use Microsoft Entra Token Credential** - Use `DefaultAzureCredential` for local development; use `ManagedIdentityCredential` or `WorkloadIdentityCredential` for production
2. **Register handlers before start** - Don't miss initial events
3. **Use groups for channels** - Organize messages by topic/room
4. **Handle reconnection** - Client auto-reconnects by default
5. **Validate in handleConnect** - Reject unauthorized connections early
6. **Use noEcho** - Prevent message echo back to sender when needed

すべてのファイル

0件のファイル

azure-web-pubsub-tsをインストール

スキルファイルをダウンロードして、.claude/skills/ ディレクトリに展開してください。

ZIPをダウンロード

リポジトリをクローンし、スキルファイルをプロジェクトにコピーしてください。

git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-typescript/skills/azure-web-pubsub-ts # Copy SKILL.md to your .claude/skills/ directory

コピー コピー
クイックセットアップ: スキルフォルダを .claude/skills/ にコピーしてください。Claude はそのスキルを自動的に検出し、使用します。
リポジトリ microsoft/skills

関連スキル

agentwallet
更新された時間 2026年7月7日
brightdata-cli
更新された時間 2026年6月29日
humanize
更新された時間 2026年7月7日
korean-stock-search
更新された時間 2026年7月8日
OR