websocket-realtime-builder
Implements real-time features using WebSockets with Socket.io, rooms, authentication, and reconnection handling. Use when users request "real-time updates", "WebSocket", "Socket.io", "live chat", or "push notifications".
What this skill does
# WebSocket Realtime Builder
Build real-time applications with WebSockets and Socket.io.
## Core Workflow
1. **Choose library**: Socket.io vs native WebSocket
2. **Setup server**: Configure WebSocket server
3. **Add authentication**: Validate connections
4. **Implement rooms**: Group connections
5. **Handle events**: Define event handlers
6. **Add reconnection**: Handle disconnects gracefully
## Installation
```bash
# Server
npm install socket.io
# Client
npm install socket.io-client
```
## Server Setup
### Basic Socket.io Server
```typescript
// server.ts
import express from 'express';
import { createServer } from 'http';
import { Server, Socket } from 'socket.io';
import { verifyToken } from './auth';
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
cors: {
origin: process.env.CLIENT_URL,
credentials: true,
},
pingInterval: 25000,
pingTimeout: 60000,
});
// Authentication middleware
io.use(async (socket, next) => {
const token = socket.handshake.auth.token;
if (!token) {
return next(new Error('Authentication required'));
}
try {
const user = await verifyToken(token);
socket.data.user = user;
next();
} catch (err) {
next(new Error('Invalid token'));
}
});
io.on('connection', (socket: Socket) => {
const user = socket.data.user;
console.log(`User connected: ${user.id}`);
// Join user's personal room
socket.join(`user:${user.id}`);
// Handle events
socket.on('disconnect', () => {
console.log(`User disconnected: ${user.id}`);
});
});
httpServer.listen(3001, () => {
console.log('Socket.io server running on port 3001');
});
export { io };
```
### Namespaces and Rooms
```typescript
// namespaces/chat.ts
import { Server, Socket } from 'socket.io';
export function setupChatNamespace(io: Server) {
const chatNamespace = io.of('/chat');
chatNamespace.on('connection', (socket: Socket) => {
const user = socket.data.user;
// Join a chat room
socket.on('join-room', async (roomId: string) => {
// Validate user can access this room
const canAccess = await canAccessRoom(user.id, roomId);
if (!canAccess) {
socket.emit('error', { message: 'Access denied' });
return;
}
socket.join(`room:${roomId}`);
socket.to(`room:${roomId}`).emit('user-joined', {
userId: user.id,
name: user.name,
});
});
// Leave a chat room
socket.on('leave-room', (roomId: string) => {
socket.leave(`room:${roomId}`);
socket.to(`room:${roomId}`).emit('user-left', {
userId: user.id,
});
});
// Send message
socket.on('send-message', async (data: { roomId: string; content: string }) => {
const { roomId, content } = data;
// Save to database
const message = await db.message.create({
data: {
roomId,
authorId: user.id,
content,
},
include: { author: true },
});
// Broadcast to room
chatNamespace.to(`room:${roomId}`).emit('new-message', {
id: message.id,
content: message.content,
author: {
id: user.id,
name: user.name,
},
createdAt: message.createdAt,
});
});
// Typing indicator
socket.on('typing-start', (roomId: string) => {
socket.to(`room:${roomId}`).emit('user-typing', {
userId: user.id,
name: user.name,
});
});
socket.on('typing-stop', (roomId: string) => {
socket.to(`room:${roomId}`).emit('user-stopped-typing', {
userId: user.id,
});
});
});
return chatNamespace;
}
```
### Event Emitters
```typescript
// services/notifications.ts
import { io } from '../server';
export class NotificationService {
// Send to specific user
static sendToUser(userId: string, event: string, data: any) {
io.to(`user:${userId}`).emit(event, data);
}
// Send to multiple users
static sendToUsers(userIds: string[], event: string, data: any) {
userIds.forEach((userId) => {
io.to(`user:${userId}`).emit(event, data);
});
}
// Broadcast to all connected users
static broadcast(event: string, data: any) {
io.emit(event, data);
}
// Send to room
static sendToRoom(roomId: string, event: string, data: any) {
io.to(`room:${roomId}`).emit(event, data);
}
// Notify new order
static notifyNewOrder(order: Order) {
// Notify customer
this.sendToUser(order.customerId, 'order:created', {
orderId: order.id,
status: order.status,
});
// Notify admins
io.to('role:admin').emit('admin:new-order', {
orderId: order.id,
customer: order.customerName,
total: order.total,
});
}
}
```
## Client Setup
### React Client Hook
```typescript
// hooks/useSocket.ts
import { useEffect, useRef, useState, useCallback } from 'react';
import { io, Socket } from 'socket.io-client';
import { useAuth } from './useAuth';
interface UseSocketOptions {
namespace?: string;
autoConnect?: boolean;
}
export function useSocket(options: UseSocketOptions = {}) {
const { namespace = '/', autoConnect = true } = options;
const { token } = useAuth();
const socketRef = useRef<Socket | null>(null);
const [isConnected, setIsConnected] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!token || !autoConnect) return;
const socket = io(`${process.env.NEXT_PUBLIC_WS_URL}${namespace}`, {
auth: { token },
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
});
socket.on('connect', () => {
setIsConnected(true);
setError(null);
});
socket.on('disconnect', () => {
setIsConnected(false);
});
socket.on('connect_error', (err) => {
setError(err.message);
setIsConnected(false);
});
socketRef.current = socket;
return () => {
socket.disconnect();
};
}, [token, namespace, autoConnect]);
const emit = useCallback((event: string, data?: any) => {
socketRef.current?.emit(event, data);
}, []);
const on = useCallback((event: string, handler: (...args: any[]) => void) => {
socketRef.current?.on(event, handler);
return () => {
socketRef.current?.off(event, handler);
};
}, []);
const off = useCallback((event: string, handler?: (...args: any[]) => void) => {
socketRef.current?.off(event, handler);
}, []);
return {
socket: socketRef.current,
isConnected,
error,
emit,
on,
off,
};
}
```
### Chat Hook
```typescript
// hooks/useChat.ts
import { useEffect, useState, useCallback } from 'react';
import { useSocket } from './useSocket';
interface Message {
id: string;
content: string;
author: { id: string; name: string };
createdAt: string;
}
interface TypingUser {
userId: string;
name: string;
}
export function useChat(roomId: string) {
const { socket, isConnected, emit, on } = useSocket({ namespace: '/chat' });
const [messages, setMessages] = useState<Message[]>([]);
const [typingUsers, setTypingUsers] = useState<TypingUser[]>([]);
// Join room on connect
useEffect(() => {
if (isConnected && roomId) {
emit('join-room', roomId);
return () => {
emit('leave-room', roomId);
};
}
}, [isConnected, roomId, emit]);
// Listen for messages
useEffect(() => {
const unsubMessage = on('new-message', (message: Message) => {
setMessages((prev) => [...prev, message]);
});
const unsubTyping = on('user-typing', (user: TypingUser) => {
setTypingUsers((prev) => {
if (prev.some((u) => u.userId === user.userId)) return prev;
return [...prev, user];
});
});
const unsubStopTyping = on('user-stopped-typing', ({ userId }: { userId: string }) => {
setTypingUsers((prev) => prev.filter((u) => u.Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.