/web-realtime-websockets
Native WebSocket API patterns, connection lifecycle, reconnection strategies, heartbeat, message typing, binary data, custom hooks
$ npx -y skills add agents-inc/skills --skill web-realtime-websockets --agent claude-codeHow it fires
How this skill gets triggered: by you, by Claude, or both.
- Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.
- You can call itInvoke it directly when you want it.
- Slash command
/web-realtime-websockets
Context preview
The summary Claude sees to decide when to auto-load this skill.
Native WebSocket API patterns, connection lifecycle, reconnection strategies, heartbeat, message typing, binary data, custom hooks
SKILL.md
web-realtime-websockets.SKILL.mdname: web-realtime-websockets
description: Native WebSocket API patterns, connection lifecycle, reconnection strategies, heartbeat, message typing, binary data, custom hooks
WebSocket Real-Time Communication Patterns
> **Quick Guide:** Use native WebSocket API for real-time bidirectional communication. Implement exponential backoff with jitter for reconnection. Use discriminated unions for type-safe message handling. Queue messages during disconnection for delivery on reconnect. Close connections on `pagehide` to allow bfcache.
---
<critical_requirements>
CRITICAL: Before Using This Skill
> **All code must follow project conventions in CLAUDE.md** (kebab-case, named exports, import ordering, `import type`, named constants)
**(You MUST implement exponential backoff with jitter for ALL reconnection logic)**
**(You MUST use discriminated unions with a `type` field for ALL WebSocket message types)**
**(You MUST queue messages during disconnection and flush on reconnect)**
**(You MUST implement heartbeat/ping-pong to detect dead connections)**
**(You MUST set `binaryType` to 'arraybuffer' when handling binary data)**
**(You MUST use wss:// for secure origins - browsers block ws:// on HTTPS pages except localhost)**
**(You MUST handle bfcache with pagehide/pageshow events)**
</critical_requirements>
---
**Auto-detection:** WebSocket, ws://, wss://, onmessage, onopen, onclose, onerror, reconnect, heartbeat, ping, pong, real-time, bidirectional
**When to use:**
- Building real-time features (chat, notifications, live updates)
- Implementing bidirectional communication between client and server
- Creating live dashboards or collaborative editing features
- Streaming data updates with low latency requirements
**When NOT to use:**
- One-way server-to-client streaming only (use SSE instead)
- Simple request-response patterns (use HTTP/REST instead)
- When library abstractions are required (use a WebSocket wrapper library)
- When automatic backpressure handling is critical (consider WebSocketStream when widely supported)
**Key patterns covered:**
- WebSocket connection lifecycle management
- Reconnection with exponential backoff and jitter
- Heartbeat/ping-pong for connection health
- Message queuing during disconnection
- Type-safe message handling with discriminated unions
- Binary data handling (ArrayBuffer, Blob)
- Custom React hooks (useWebSocket)
- Authentication patterns
- Room/channel subscriptions
- bfcache compatibility
**Detailed Resources:**
- [examples/core.md](examples/core.md) - Connection lifecycle, reconnection, heartbeat, queuing, auth, rooms, hooks
- [examples/state-machine.md](examples/state-machine.md) - Connection state machine pattern
- [examples/binary.md](examples/binary.md) - Binary data and file upload
- [examples/presence.md](examples/presence.md) - User presence detection
- [reference.md](reference.md) - Decision frameworks, close codes, anti-patterns
---
<philosophy>
Philosophy
WebSockets provide full-duplex communication channels over a single TCP connection, enabling real-time bidirectional data flow between client and server. Unlike HTTP, WebSocket connections remain open, eliminating the overhead of repeated handshakes.
**The native WebSocket API is simple but requires careful handling:**
1. **Connection Resilience:** Networks are unreliable. Always implement reconnection with exponential backoff and jitter to prevent thundering herd problems.
2. **Connection Health:** Intermediate proxies and firewalls can silently drop idle connections. Heartbeats detect dead connections and keep connections alive.
3. **Message Integrity:** Messages sent during disconnection are lost. Queue them and flush on reconnect for reliable delivery.
4. **Type Safety:** WebSocket messages are untyped strings. Use discriminated unions with a shared `type` field for compile-time safety.
5. **bfcache Compatibility:** Open WebSocket connections prevent pages from using the browser's back/forward cache, degrading navigation performance. Close connections on `pagehide` and reconnect on `pageshow` when `event.persisted`.
**Connection Lifecycle:**
CONNECTING -> OPEN <-> (messages) -> CLOSING -> CLOSED
| |
(error) <- reconnect <- (close)</philosophy>
---
<patterns>
Core Patterns
Pattern 1: Basic WebSocket Connection
The native WebSocket API provides four lifecycle events: `onopen`, `onmessage`, `onerror`, and `onclose`. Always handle all four.
const WS_URL = "wss://api.example.com/ws";
const socket = new WebSocket(WS_URL);
socket.onopen = () => {
/* connection ready - safe to send */
};
socket.onmessage = (event: MessageEvent) => {
/* JSON.parse(event.data) */
};
socket.onerror = (event: Event) => {
/* always followed by onclose */
};
socket.onclose = (event: CloseEvent) => {
/* reconnect here */
};**Why good:** All four lifecycle events handled, typed event parameters, named constant for URL
> Full implementation: [examples/core.md](examples/core.md) Pattern 1
---
Pattern 2: Exponential Backoff with Jitter
Reconnection attempts must use exponential backoff with jitter to prevent all clients from reconnecting simultaneously (thundering herd problem). Cap delay at a maximum and limit total retry attempts.
const INITIAL_BACKOFF_MS = 1000;
const MAX_BACKOFF_MS = 30000;
const BACKOFF_MULTIPLIER = 2;
const JITTER_FACTOR = 0.5;
function calculateBackoff(attempt: number): number {
const exponential = Math.min(
INITIAL_BACKOFF_MS * Math.pow(BACKOFF_MULTIPLIER, attempt),
MAX_BACKOFF_MS,
);
const jitter = exponential * JITTER_FACTOR * (Math.random() * 2 - 1);
return Math.floor(exponential + jitter);
}**Why good:** Jitter prevents thundering herd, capped maximum delay, retry limit prevents infinite loops
> Full reconnecting class: [examples/core.md](examples/core.md) Pattern 2
---
Pattern 3: Heartbeat/Ping-
Read more
name: web-realtime-websockets description: Native WebSocket API patterns, connection lifecycle, reconnection strategies, heartbeat, message typing, binary data, custom hooks
WebSocket Real-Time Communication Patterns
> **Quick Guide:** Use native WebSocket API for real-time bidirectional communication. Implement exponential backoff with jitter for reconnection. Use discriminated unions for type-safe message handling. Queue messages during disconnection for delivery on reconnect. Close connections on `pagehide` to allow bfcache.
---
<critical_requirements>
CRITICAL: Before Using This Skill
> **All code must follow project conventions in CLAUDE.md** (kebab-case, named exports, import ordering, `import type`, named constants)
**(You MUST implement exponential backoff with jitter for ALL reconnection logic)**
**(You MUST use discriminated unions with a `type` field for ALL WebSocket message types)**
**(You MUST queue messages during disconnection and flush on reconnect)**
**(You MUST implement heartbeat/ping-pong to detect dead connections)**
**(You MUST set `binaryType` to 'arraybuffer' when handling binary data)**
**(You MUST use wss:// for secure origins - browsers block ws:// on HTTPS pages except localhost)**
**(You MUST handle bfcache with pagehide/pageshow events)**
</critical_requirements>
---
**Auto-detection:** WebSocket, ws://, wss://, onmessage, onopen, onclose, onerror, reconnect, heartbeat, ping, pong, real-time, bidirectional
**When to use:**
- Building real-time features (chat, notifications, live updates)
- Implementing bidirectional communication between client and server
- Creating live dashboards or collaborative editing features
- Streaming data updates with low latency requirements
**When NOT to use:**
- One-way server-to-client streaming only (use SSE instead)
- Simple request-response patterns (use HTTP/REST instead)
- When library abstractions are required (use a WebSocket wrapper library)
- When automatic backpressure handling is critical (consider WebSocketStream when widely supported)
**Key patterns covered:**
- WebSocket connection lifecycle management
- Reconnection with exponential backoff and jitter
- Heartbeat/ping-pong for connection health
- Message queuing during disconnection
- Type-safe message handling with discriminated unions
- Binary data handling (ArrayBuffer, Blob)
- Custom React hooks (useWebSocket)
- Authentication patterns
- Room/channel subscriptions
- bfcache compatibility
**Detailed Resources:**
- [examples/core.md](examples/core.md) - Connection lifecycle, reconnection, heartbeat, queuing, auth, rooms, hooks
- [examples/state-machine.md](examples/state-machine.md) - Connection state machine pattern
- [examples/binary.md](examples/binary.md) - Binary data and file upload
- [examples/presence.md](examples/presence.md) - User presence detection
- [reference.md](reference.md) - Decision frameworks, close codes, anti-patterns
---
<philosophy>
Philosophy
WebSockets provide full-duplex communication channels over a single TCP connection, enabling real-time bidirectional data flow between client and server. Unlike HTTP, WebSocket connections remain open, eliminating the overhead of repeated handshakes.
**The native WebSocket API is simple but requires careful handling:**
1. **Connection Resilience:** Networks are unreliable. Always implement reconnection with exponential backoff and jitter to prevent thundering herd problems.
2. **Connection Health:** Intermediate proxies and firewalls can silently drop idle connections. Heartbeats detect dead connections and keep connections alive.
3. **Message Integrity:** Messages sent during disconnection are lost. Queue them and flush on reconnect for reliable delivery.
4. **Type Safety:** WebSocket messages are untyped strings. Use discriminated unions with a shared `type` field for compile-time safety.
5. **bfcache Compatibility:** Open WebSocket connections prevent pages from using the browser's back/forward cache, degrading navigation performance. Close connections on `pagehide` and reconnect on `pageshow` when `event.persisted`.
**Connection Lifecycle:**
CONNECTING -> OPEN <-> (messages) -> CLOSING -> CLOSED
| |
(error) <- reconnect <- (close)</philosophy>
---
<patterns>
Core Patterns
Pattern 1: Basic WebSocket Connection
The native WebSocket API provides four lifecycle events: `onopen`, `onmessage`, `onerror`, and `onclose`. Always handle all four.
const WS_URL = "wss://api.example.com/ws";
const socket = new WebSocket(WS_URL);
socket.onopen = () => {
/* connection ready - safe to send */
};
socket.onmessage = (event: MessageEvent) => {
/* JSON.parse(event.data) */
};
socket.onerror = (event: Event) => {
/* always followed by onclose */
};
socket.onclose = (event: CloseEvent) => {
/* reconnect here */
};**Why good:** All four lifecycle events handled, typed event parameters, named constant for URL
> Full implementation: [examples/core.md](examples/core.md) Pattern 1
---
Pattern 2: Exponential Backoff with Jitter
Reconnection attempts must use exponential backoff with jitter to prevent all clients from reconnecting simultaneously (thundering herd problem). Cap delay at a maximum and limit total retry attempts.
const INITIAL_BACKOFF_MS = 1000;
const MAX_BACKOFF_MS = 30000;
const BACKOFF_MULTIPLIER = 2;
const JITTER_FACTOR = 0.5;
function calculateBackoff(attempt: number): number {
const exponential = Math.min(
INITIAL_BACKOFF_MS * Math.pow(BACKOFF_MULTIPLIER, attempt),
MAX_BACKOFF_MS,
);
const jitter = exponential * JITTER_FACTOR * (Math.random() * 2 - 1);
return Math.floor(exponential + jitter);
}**Why good:** Jitter prevents thundering herd, capped maximum delay, retry limit prevents infinite loops
> Full reconnecting class: [examples/core.md](examples/core.md) Pattern 2
---
Pattern 3: Heartbeat/Ping-
Showing the first part of this file.
The official skills marketplace for Agents Inc. 150+ skills covering everything from React and Prisma to Redis, ElevenLabs, and infrastructure tooling. Pick the skills that match your stack and install them via Claude Code. Need more control?
Repo: agents-inc/skills
Other skills on agents-inc-skills.
- /ai-infrastructure-huggingface-inference
Hugging Face Inference SDK patterns for TypeScript/Node.js — InferenceClient setup, chat completion, text generation, streaming, embeddings, image generation, audio transcription, translation, summarization, and Inference Endpoints
Open skill - /ai-infrastructure-litellm
LiteLLM proxy server setup, TypeScript client patterns via OpenAI SDK, model routing, fallbacks, load balancing, spend tracking, virtual keys, and production deployment
Open skill - /ai-infrastructure-modal
Serverless GPU compute platform for AI model deployment — web endpoints, GPU functions, model serving, and TypeScript client patterns
Open skill - /ai-infrastructure-ollama
Local LLM inference with the Ollama JavaScript client -- chat, streaming, tool calling, vision, embeddings, structured output, model management, and OpenAI-compatible endpoint
Open skill - /ai-infrastructure-replicate
Replicate SDK patterns for TypeScript/Node.js -- client setup, predictions, streaming, webhooks, file handling, model versioning, deployments, and training
Open skill - /ai-infrastructure-together-ai
Together AI SDK patterns for TypeScript — client setup, chat completions, streaming, structured output, function calling, embeddings, image generation, fine-tuning, and OpenAI-compatible endpoints
Open skill

