option
MaisonMaison Skill Développement d'API azure-web-pubsub-ts

azure-web-pubsub-ts

microsoft/skills microsoft/skills

Créez des applications de messagerie en temps réel à l'aide des SDK Azure Web PubSub pour JavaScript, y compris la gestion côté serveur, la publication/abonnement côté client et les gestionnaires d'événements Express.

...Développer tout
1
Heure mise à jour 13 septembre 2026

SDK Azure Web PubSub pour TypeScript

Messagerie en temps réel avec des connexions WebSocket et des modèles de publication/souscription.

Installation

# Gestion côté serveur
npm install @azure/web-pubsub @azure/identity

# Messagerie en temps réel côté client
npm install @azure/web-pubsub-client

# Middleware Express pour les gestionnaires d'événements
npm install @azure/web-pubsub-express

Variables d'environnement

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 # Requis uniquement si DefaultAzureCredential est utilisé en production
</resource></key></resource>

Côté serveur : WebPubSubServiceClient

Authentification

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

// Développement local : DefaultAzureCredential. Production : définir AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<specific_credential>
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// Ou utiliser un identifiant spécifique directement en production :
// Voir https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest#credential-classes
// const credential = new ManagedIdentityCredential();

// Chaîne de connexion
const client = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_CONNECTION_STRING!,
  "chat"  // nom du hub
);

// Identifiant de jeton Microsoft Entra (recommandé)
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>

Générer un jeton d'accès client

// Jeton de base
const token = await client.getClientAccessToken();
console.log(token.url);  // wss://...?access_token=...

// Jeton avec identifiant utilisateur
const userToken = await client.getClientAccessToken({
  userId: "user123",
});

// Jeton avec autorisations
const permToken = await client.getClientAccessToken({
  userId: "user123",
  roles: [
    "webpubsub.joinLeaveGroup",
    "webpubsub.sendToGroup",
    "webpubsub.sendToGroup.chat-room",  // groupe spécifique
  ],
  groups: ["chat-room"],  // rejoindre automatiquement lors de la connexion
  expirationTimeInMinutes: 60,
});

Envoyer des messages

// Diffusion à toutes les connexions du hub
await client.sendToAll({ message: "Bonjour à tous !" });
await client.sendToAll("Texte brut", { contentType: "text/plain" });

// Envoyer à un utilisateur spécifique (toutes ses connexions)
await client.sendToUser("user123", { message: "Bonjour !" });

// Envoyer à une connexion spécifique
await client.sendToConnection("connectionId", { data: "Message direct" });

// Envoyer avec un filtre (syntaxe OData)
await client.sendToAll({ message: "Filtré" }, {
  filter: "userId ne 'admin'",
});

Gestion des groupes

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

// Ajouter un utilisateur/une connexion au groupe
await group.addUser("user123");
await group.addConnection("connectionId");

// Retirer du groupe
await group.removeUser("user123");

// Envoyer au groupe
await group.sendToAll({ message: "Message de groupe" });

// Fermer toutes les connexions du groupe
await group.closeAllConnections({ reason: "Maintenance" });

Gestion des connexions

// Vérifier l'existence
const userExists = await client.userExists("user123");
const connExists = await client.connectionExists("connectionId");

// Fermer les connexions
await client.closeConnection("connectionId", { reason: "Exclu" });
await client.closeUserConnections("user123");
await client.closeAllConnections();

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

Côté client : WebPubSubClient

Connexion

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

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

// URL dynamique depuis le point de terminaison de négociation
const client2 = new WebPubSubClient({
  getClientAccessUrl: async () => {
    const response = await fetch("/negotiate");
    const { url } = await response.json();
    return url;
  },
});

// Enregistrer les gestionnaires AVANT le démarrage
client.on("connected", (e) => {
  console.log(`Connecté : ${e.connectionId}`);
});

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

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

Envoyer des messages

// Rejoindre d'abord le groupe
await client.joinGroup("chat-room");

// Envoyer au groupe
await client.sendToGroup("chat-room", "Bonjour !", "text");
await client.sendToGroup("chat-room", { type: "message", content: "Salut" }, "json");

// Options d'envoi
await client.sendToGroup("chat-room", "Bonjour", "text", {
  noEcho: true,        // Ne pas renvoyer l'écho à l'expéditeur
  fireAndForget: true, // Ne pas attendre l'accusé de réception
});

// Envoyer un événement au serveur
await client.sendEvent("userAction", { action: "saisie" }, "json");

Gestionnaires d'événements

// Cycle de vie de la connexion
client.on("connected", (e) => {
  console.log(`Connecté : ${e.connectionId}, Utilisateur : ${e.userId}`);
});

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

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

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

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

// Échec de rejoindre le groupe
client.on("rejoin-group-failed", (e) => {
  console.log(`Échec de rejoindre ${e.group} : ${e.error}`);
});

Gestionnaire d'événements 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/",

  // Bloquant : approuver/rejeter la connexion
  handleConnect: (req, res) => {
    if (!req.claims?.sub) {
      res.fail(401, "Authentification requise");
      return;
    }
    res.success({
      userId: req.claims.sub[0],
      groups: ["general"],
      roles: ["webpubsub.sendToGroup"],
    });
  },

  // Bloquant : gérer les événements personnalisés
  handleUserEvent: (req, res) => {
    console.log(`Événement de ${req.context.userId} :`, req.data);
    res.success(`Reçu : ${req.data}`, "text");
  },

  // Non bloquant
  onConnected: (req) => {
    console.log(`Client connecté : ${req.context.connectionId}`);
  },

  onDisconnected: (req) => {
    console.log(`Client déconnecté : ${req.context.connectionId}`);
  },
});

app.use(handler.getMiddleware());

// Point de terminaison de négociation
app.get("/negotiate", async (req, res) => {
  const token = await serviceClient.getClientAccessToken({
    userId: req.user?.id,
  });
  res.json({ url: token.url });
});

app.listen(8080);

Types clés

// Serveur
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";

Bonnes pratiques

  1. Utiliser l'identifiant de jeton Microsoft Entra - Utiliser DefaultAzureCredential pour le développement local ; utiliser ManagedIdentityCredential ou WorkloadIdentityCredential pour la production
  2. Enregistrer les gestionnaires avant le démarrage - Ne pas manquer les événements initiaux
  3. Utiliser des groupes pour les canaux - Organiser les messages par sujet/salle
  4. Gérer la reconnexion - Le client se reconnecte automatiquement par défaut
  5. Valider dans handleConnect - Rejeter les connexions non autorisées tôt
  6. Utiliser noEcho - Empêcher le renvoi de l'écho du message à l'expéditeur lorsque cela est nécessaire
Voir sur 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

Tous les fichiers

0 fichiers

Installer azure-web-pubsub-ts

Téléchargez et extrayez les fichiers de compétences dans votre répertoire .claude/skills/.

Télécharger le ZIP

Clonez le dépôt et copiez les fichiers de compétence dans votre projet.

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

Copier Copier
Configuration rapide: Copiez le dossier de l’extension dans .claude/skills/ Claude détectera et utilisera automatiquement l’extension

Compétences similaires

brightdata-cli
Heure mise à jour 29 juin 2026
humanize
Heure mise à jour 7 juillet 2026
agentwallet
Heure mise à jour 7 juillet 2026
korean-stock-search
Heure mise à jour 8 juillet 2026
OR