opción
HogarHogar Skill Desarrollo de API azure-web-pubsub-ts

azure-web-pubsub-ts

microsoft/skills microsoft/skills

Construye aplicaciones de mensajería en tiempo real utilizando los SDKs de Azure Web PubSub para JavaScript, que incluyen la gestión del lado del servidor, la publicación/suscripción del lado del cliente y los controladores de eventos de Express.

...Expandir todo
0
Tiempo actualizado 13 de septiembre de 2026

SDK de Azure Web PubSub para TypeScript

Mensajería en tiempo real con conexiones WebSocket y patrones de publicación/suscripción.

Instalación

# Gestión del lado del servidor
npm install @azure/web-pubsub @azure/identity

# Mensajería en tiempo real del lado del cliente
npm install @azure/web-pubsub-client

# Middleware de Express para controladores de eventos
npm install @azure/web-pubsub-express

Variables de entorno

WEBPUBSUB_CONNECTION_STRING=Endpoint=https://<recurso>.webpubsub.azure.com;AccessKey=<clave>;Version=1.0;
WEBPUBSUB_ENDPOINT=https://<recurso>.webpubsub.azure.com
AZURE_TOKEN_CREDENTIALS=prod # Solo es necesario si se utiliza DefaultAzureCredential en producción
</recurso></clave></recurso>

Lado del servidor: WebPubSubServiceClient

Autenticación

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

// Desarrollo local: DefaultAzureCredential. Producción: establecer AZURE_TOKEN_CREDENTIALS=prod o AZURE_TOKEN_CREDENTIALS=<credencial_específica>
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// O utilizar una credencial específica directamente en producción:
// Consulte https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest#credential-classes
// const credential = new ManagedIdentityCredential();

// Cadena de conexión
const client = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_CONNECTION_STRING!,
  "chat"  // nombre del hub
);

// Credencial de token de Microsoft Entra (recomendado)
const client2 = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_ENDPOINT!,
  credential,
  "chat"
);

// AzureKeyCredential
const client3 = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_ENDPOINT!,
  new AzureKeyCredential("<clave-de-acceso>"),
  "chat"
);
</clave-de-acceso></credencial_específica>

Generar token de acceso del cliente

// Token básico
const token = await client.getClientAccessToken();
console.log(token.url);  // wss://...?access_token=...

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

// Token con permisos
const permToken = await client.getClientAccessToken({
  userId: "user123",
  roles: [
    "webpubsub.joinLeaveGroup",
    "webpubsub.sendToGroup",
    "webpubsub.sendToGroup.chat-room",  // grupo específico
  ],
  groups: ["chat-room"],  // unirse automáticamente al conectar
  expirationTimeInMinutes: 60,
});

Enviar mensajes

// Transmitir a todas las conexiones en el hub
await client.sendToAll({ message: "¡Hola a todos!" });
await client.sendToAll("Texto plano", { contentType: "text/plain" });

// Enviar a un usuario específico (todas sus conexiones)
await client.sendToUser("user123", { message: "¡Hola!" });

// Enviar a una conexión específica
await client.sendToConnection("connectionId", { data: "Mensaje directo" });

// Enviar con filtro (sintaxis OData)
await client.sendToAll({ message: "Filtrado" }, {
  filter: "userId ne 'admin'",
});

Gestión de grupos

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

// Añadir usuario/conexión al grupo
await group.addUser("user123");
await group.addConnection("connectionId");

// Eliminar del grupo
await group.removeUser("user123");

// Enviar al grupo
await group.sendToAll({ message: "Mensaje del grupo" });

// Cerrar todas las conexiones en el grupo
await group.closeAllConnections({ reason: "Mantenimiento" });

Gestión de conexiones

// Comprobar existencia
const userExists = await client.userExists("user123");
const connExists = await client.connectionExists("connectionId");

// Cerrar conexiones
await client.closeConnection("connectionId", { reason: "Expulsado" });
await client.closeUserConnections("user123");
await client.closeAllConnections();

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

Lado del cliente: WebPubSubClient

Conectar

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

// URL directa
const client = new WebPubSubClient("<url-de-acceso-del-cliente>");

// URL dinámica desde el punto de enlace de negociación
const client2 = new WebPubSubClient({
  getClientAccessUrl: async () => {
    const response = await fetch("/negotiate");
    const { url } = await response.json();
    return url;
  },
});

// Registrar controladores ANTES de iniciar
client.on("connected", (e) => {
  console.log(`Conectado: ${e.connectionId}`);
});

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

await client.start();
</url-de-acceso-del-cliente>

Enviar mensajes

// Unirse al grupo primero
await client.joinGroup("chat-room");

// Enviar al grupo
await client.sendToGroup("chat-room", "¡Hola!", "text");
await client.sendToGroup("chat-room", { type: "message", content: "Hola" }, "json");

// Opciones de envío
await client.sendToGroup("chat-room", "Hola", "text", {
  noEcho: true,        // No reenviar al remitente
  fireAndForget: true, // No esperar confirmación
});

// Enviar evento al servidor
await client.sendEvent("userAction", { action: "typing" }, "json");

Controladores de eventos

// Ciclo de vida de la conexión
client.on("connected", (e) => {
  console.log(`Conectado: ${e.connectionId}, Usuario: ${e.userId}`);
});

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

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

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

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

// Fallo al volver a unirse
client.on("rejoin-group-failed", (e) => {
  console.log(`No se pudo volver a unirse a ${e.group}: ${e.error}`);
});

Controlador de eventos de 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/",

  // Bloqueante: aprobar/rechazar conexión
  handleConnect: (req, res) => {
    if (!req.claims?.sub) {
      res.fail(401, "Autenticación requerida");
      return;
    }
    res.success({
      userId: req.claims.sub[0],
      groups: ["general"],
      roles: ["webpubsub.sendToGroup"],
    });
  },

  // Bloqueante: manejar eventos personalizados
  handleUserEvent: (req, res) => {
    console.log(`Evento de ${req.context.userId}:`, req.data);
    res.success(`Recibido: ${req.data}`, "text");
  },

  // No bloqueante
  onConnected: (req) => {
    console.log(`Cliente conectado: ${req.context.connectionId}`);
  },

  onDisconnected: (req) => {
    console.log(`Cliente desconectado: ${req.context.connectionId}`);
  },
});

app.use(handler.getMiddleware());

// Punto de enlace de negociación
app.get("/negotiate", async (req, res) => {
  const token = await serviceClient.getClientAccessToken({
    userId: req.user?.id,
  });
  res.json({ url: token.url });
});

app.listen(8080);

Tipos clave

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

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

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

Mejores prácticas

  1. Utilizar credencial de token de Microsoft Entra - Utilizar DefaultAzureCredential para el desarrollo local; utilizar ManagedIdentityCredential o WorkloadIdentityCredential para producción
  2. Registrar controladores antes de iniciar - No perderse los eventos iniciales
  3. Utilizar grupos para canales - Organizar mensajes por tema/sala
  4. Gestionar la reconexión - El cliente se reconecta automáticamente de forma predeterminada
  5. Validar en handleConnect - Rechazar conexiones no autorizadas temprano
  6. Utilizar noEcho - Evitar el reenvío del mensaje al remitente cuando sea necesario
Ver en 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

Todos los archivos

0 archivos

Instalar azure-web-pubsub-ts

Descarga y extrae los archivos de habilidades en tu directorio .claude/skills/.

Descargar ZIP

Clona el repositorio y copia los archivos de la habilidad a tu proyecto.

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

Copiar Copiar
Configuración rápida: Copia la carpeta de la habilidad a .claude/skills/ Claude detectará y utilizará automáticamente la habilidad
Repositorio microsoft/skills

Habilidades relacionadas

brightdata-cli
Tiempo actualizado 29 de junio de 2026
humanize
Tiempo actualizado 7 de julio de 2026
agentwallet
Tiempo actualizado 7 de julio de 2026
korean-stock-search
Tiempo actualizado 8 de julio de 2026
OR