Overview
Provides complete guidance and code for integrating native WebSockets or Socket.io into web apps, including reconnection with exponential backoff, message envelope format, React hook for lifecycle management, server-side setup (Node/ws or Socket.io), error handling, and authentication patterns for real-time features.
When to Use This Skill
- Adding live chat, notifications, presence indicators, collaborative editing, or live data dashboards.
- The user mentions "real-time", "WebSocket", "live updates", "push", or "socket".
Prerequisites
- Backend that can run a WebSocket server (Node.js, Deno, or cloud service like Pusher, Ably, Supabase Realtime).
- Frontend framework (React, vanilla, etc.).
- For production: load balancer that supports WebSocket upgrade (Nginx, ALB, etc.).
Steps
- Choose transport: Native WebSocket (lightweight) vs Socket.io (more features, fallback).
- Define message protocol (JSON envelope):
{ "type": "chat.message", "payload": {...}, "id": "uuid", "timestamp": "..." }
- Client implementation:
- Connection, onopen, onmessage, onerror, onclose.
- Reconnection logic with backoff (max 5 attempts, then show "reconnecting" UI).
- Heartbeat / ping-pong for keepalive.
- React hook (
useWebSocket): manages connection, auto-reconnect, typed message handlers.
- Server side: auth on connection (JWT in query or subprotocol), room management, broadcast.
- Security: validate all incoming messages, rate limit, authenticate every connection.
- Output: full hook, example chat component, server route, deployment notes.
Examples
Complete useWebSocket.ts hook, a simple chat UI, and a minimal Node + ws server example are provided.
Edge Cases & Error Handling
- Network drops: exponential backoff + user notification.
- Auth expiration: refresh token and reconnect.
- Large messages: chunk or use binary when appropriate.
- Browser tab sleep: handle visibilitychange to pause/reconnect.
Verification
- Open two browser tabs — messages appear in real time.
- Kill the server — client shows reconnecting UI and recovers when server restarts.
- Check browser console for clean connection lifecycle.
- Success: Real-time features work reliably with graceful degradation.
References
1---2name: websocket-integration3description: Integrates WebSocket real-time communication into a web application. Use when implementing live features like chat, notifications, collaborative editing, or live dashboards.4license: Apache-2.05compatibility: Claude Code, Codex, Gemini CLI6metadata:7 author: ai-skills8 version: "1.0"9 category: web-development10 tags: websocket, realtime, chat, notifications, socket.io, native-websocket11---1213## Overview1415Provides complete guidance and code for integrating native WebSockets or Socket.io into web apps, including reconnection with exponential backoff, message envelope format, React hook for lifecycle management, server-side setup (Node/ws or Socket.io), error handling, and authentication patterns for real-time features.1617## When to Use This Skill1819- Adding live chat, notifications, presence indicators, collaborative editing, or live data dashboards.20- The user mentions "real-time", "WebSocket", "live updates", "push", or "socket".2122## Prerequisites2324- Backend that can run a WebSocket server (Node.js, Deno, or cloud service like Pusher, Ably, Supabase Realtime).25- Frontend framework (React, vanilla, etc.).26- For production: load balancer that supports WebSocket upgrade (Nginx, ALB, etc.).2728## Steps29301. **Choose transport**: Native WebSocket (lightweight) vs Socket.io (more features, fallback).312. **Define message protocol** (JSON envelope):32 ```json33 { "type": "chat.message", "payload": {...}, "id": "uuid", "timestamp": "..." }34 ```353. **Client implementation**:36 - Connection, onopen, onmessage, onerror, onclose.37 - Reconnection logic with backoff (max 5 attempts, then show "reconnecting" UI).38 - Heartbeat / ping-pong for keepalive.394. **React hook** (`useWebSocket`): manages connection, auto-reconnect, typed message handlers.405. **Server side**: auth on connection (JWT in query or subprotocol), room management, broadcast.416. **Security**: validate all incoming messages, rate limit, authenticate every connection.427. **Output**: full hook, example chat component, server route, deployment notes.4344## Examples4546Complete `useWebSocket.ts` hook, a simple chat UI, and a minimal Node + ws server example are provided.4748## Edge Cases & Error Handling4950- Network drops: exponential backoff + user notification.51- Auth expiration: refresh token and reconnect.52- Large messages: chunk or use binary when appropriate.53- Browser tab sleep: handle visibilitychange to pause/reconnect.5455## Verification56571. Open two browser tabs — messages appear in real time.582. Kill the server — client shows reconnecting UI and recovers when server restarts.593. Check browser console for clean connection lifecycle.604. Success: Real-time features work reliably with graceful degradation.6162## References6364- [MDN WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)65- [Socket.io Docs](https://socket.io/docs/v4/)66- [ws library (Node)](https://github.com/websockets/ws)