dinaf2026-web/awesome-web-skills/web-realtime

Claude Code and agent skill by dinaf2026-web/awesome-web-skills

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Real-time feature patterns for modern web apps — WebSockets, Server-Sent Events, Pusher/Ably, live counters, collaborative editing, and presence indicators.

Install

npx vskill@latest install dinaf2026-web/awesome-web-skills/web-realtime

SKILL.md

The same SKILL.md was published earlier as dinaf2026-web/awesome-web-skills/web-realtime.

web-realtime

Real-time feature patterns for modern web apps. Covers transport selection, server setup, client hooks, presence, collaboration, and production scale concerns.


1. When to Use Which

TransportLatencyDirectionServer LoadBest For
SSELowServer → Client onlyLowFeeds, notifications, live scores
WebSocketVery lowBidirectionalMediumChat, games, collaborative editing
Long PollingMediumServer → ClientHighLegacy fallback, simple alerts
Short PollingHighClient → ServerVery highLast resort, infrequent updates
Pusher/AblyLowBidirectional (managed)None (offloaded)Presence, auth channels, rapid prototyping

Decision rules:

  • Client only needs to receive → use SSE
  • Client needs to send and receive → use WebSocket or Pusher/Ably
  • You need auth'd private channels or presence out of the box → use Pusher or Ably
  • You control infra and need zero vendor dependency → use ws (WebSocket)
  • You need < 1 hour to ship → use Pusher or Ably

2. Server-Sent Events in Next.js

Route Handler (App Router)
ts
// app/api/stream/route.ts
import { NextRequest } from 'next/server'
export const runtime = 'edge' // or 'nodejs'
export async function GET(req: NextRequest) {
const encoder = new TextEncoder()
const stream = new ReadableStream({
async start(controller) {
const send = (event: string, data: unknown) => {
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`
controller.enqueue(encoder.encode(payload))
}
// Send initial state
send('connected', { ts: Date.now() })
// Example: push updates every 2 s (replace with your event source)
const interval = setInterval(() => {
send('update', { count: Math.floor(Math.random() * 100), ts: Date.now() })
}, 2000)
// Clean up when client disconnects
req.signal.addEventListener('abort', () => {
clearInterval(interval)
controller.close()
})
},
})
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no', // Disable Nginx buffering
},
})
}
EventSource Client Hook
ts
// hooks/useSSE.ts
import { useEffect, useRef, useState } from 'react'
type SSEStatus = 'connecting' | 'open' | 'closed' | 'error'
interface SSEOptions {
onMessage?: (event: MessageEvent) => void
onEvent?: (type: string, data: unknown) => void
withCredentials?: boolean
retryInterval?: number
}
export function useSSE(url: string, options: SSEOptions = {}) {
const { onMessage, onEvent, withCredentials = false, retryInterval = 3000 } = options
const [status, setStatus] = useState<SSEStatus>('connecting')
const esRef = useRef<EventSource | null>(null)
const retryTimer = useRef<ReturnType<typeof setTimeout>>()
useEffect(() => {
let cancelled = false
const connect = () => {
if (cancelled) return
const es = new EventSource(url, { withCredentials })
esRef.current = es
es.onopen = () => setStatus('open')
es.onerror = () => {
setStatus('error')
es.close()
retryTimer.current = setTimeout(connect, retryInterval)
}
es.onmessage = (e) => onMessage?.(e)
// Forward named events
const handler = (e: MessageEvent) => {
try {
onEvent?.(e.type, JSON.parse(e.data))
} catch {
onEvent?.(e.type, e.data)
}
}
// Attach common named events — add yours here
;['update', 'notification', 'presence', 'cursor'].forEach((ev) =>
es.addEventListener(ev, handler as EventListener)
)
}
connect()
return () => {
cancelled = true
clearTimeout(retryTimer.current)
esRef.current?.close()
setStatus('closed')
}
}, [url])
return { status }
}
Usage
tsx
// components/LiveFeed.tsx
export function LiveFeed() {
const [items, setItems] = useState<FeedItem[]>([])
const { status } = useSSE('/api/stream', {
onEvent(type, data) {
if (type === 'update') {
setItems((prev) => [data as FeedItem, ...prev].slice(0, 50))
}
},
})
return (
<div>
<ConnectionBadge status={status} />
{items.map((item) => <FeedCard key={item.id} item={item} />)}
</div>
)
}

3. WebSocket with ws Library

Server Setup (Node / Express)
ts
// server/ws.ts
import { WebSocketServer, WebSocket } from 'ws'
import { IncomingMessage } from 'http'
import { parse } from 'url'
interface Client {
ws: WebSocket
id: string
room: string
userId?: string
}
const clients = new Map<string, Client>()
export function createWSServer(server: import('http').Server) {
const wss = new WebSocketServer({ server, path: '/ws' })
wss.on('connection', (ws: WebSocket, req: IncomingMessage) => {
const { query } = parse(req.url ?? '', true)
const room = (query.room as string) ?? 'default'
const userId = query.userId as string | undefined
const id = crypto.randomUUID()
clients.set(id, { ws, id, room, userId })
ws.on('message', (raw) => {
try {
const msg = JSON.parse(raw.toString())
handleMessage(id, msg)
} catch {
// ignore malformed
}
})
ws.on('close', () => {
clients.delete(id)
broadcast(room, { type: 'presence', userId, online: false })
})
ws.on('error', (err) => console.error('ws error', err))
// Acknowledge connection
send(ws, { type: 'connected', id })
broadcast(room, { type: 'presence', userId, online: true }, id)
})
return wss
}
function handleMessage(senderId: string, msg: Record<string, unknown>) {
const client = clients.get(senderId)
if (!client) return
switch (msg.type) {
case 'message':
broadcast(client.room, { ...msg, senderId })
break
case 'cursor':
broadcast(client.room, { ...msg, senderId }, senderId)
break
case 'ping':
send(client.ws, { type: 'pong' })
break
}
}
function broadcast(room: string, payload: unknown, excludeId?: string) {
const data = JSON.stringify(payload)
for (const [id, client] of clients) {
if (id === excludeId) continue
if (client.room !== room) continue
if (client.ws.readyState === WebSocket.OPEN) {
client.ws.send(data)
}
}
}
function send(ws: WebSocket, payload: unknown) {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(payload))
}
}
Client Hook with Reconnection
ts
// hooks/useWebSocket.ts
import { useEffect, useRef, useState, useCallback } from 'react'
type WSStatus = 'connecting' | 'open' | 'closing' | 'closed'
interface UseWebSocketOptions {
onMessage: (msg: unknown) => void
reconnectDelay?: number
maxReconnectDelay?: number
}
export function useWebSocket(url: string, options: UseWebSocketOptions) {
const { onMessage, reconnectDelay = 1000, maxReconnectDelay = 30_000 } = options
const [status, setStatus] = useState<WSStatus>('connecting')
const wsRef = useRef<WebSocket | null>(null)
const reconnectAttempts = useRef(0)
const reconnectTimer = useRef<ReturnType<typeof setTimeout>>()
const isMounted = useRef(true)
const connect = useCallback(() => {
if (!isMounted.current) return
const ws = new WebSocket(url)
wsRef.current = ws
setStatus('connecting')
ws.onopen = () => {
setStatus('open')
reconnectAttempts.current = 0
}
ws.onclose = () => {
setStatus('closed')
if (!isMounted.current) return
const delay = Math.min(
reconnectDelay * 2 ** reconnectAttempts.current,
maxReconnectDelay
)
reconnectAttempts.current += 1
reconnectTimer.current = setTimeout(connect, delay)
}
ws.onerror = () => {
ws.close()
}
ws.onmessage = (e) => {
try {
onMessage(JSON.parse(e.data))
} catch {
onMessage(e.data)
}
}
}, [url, onMessage, reconnectDelay, maxReconnectDelay])
useEffect(() => {
isMounted.current = true
connect()
return () => {
isMounted.current = false
clearTimeout(reconnectTimer.current)
wsRef.current?.close()
}
}, [connect])
const send = useCallback((payload: unknown) => {
const ws = wsRef.current
if (ws?.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(payload))
}
}, [])
return { send, status }
}

4. Pusher Setup

Install
bash
npm install pusher pusher-js
Server — Trigger Event
ts
// lib/pusher-server.ts
import Pusher from 'pusher'
export const pusherServer = new Pusher({
appId: process.env.PUSHER_APP_ID!,
key: process.env.NEXT_PUBLIC_PUSHER_KEY!,
secret: process.env.PUSHER_SECRET!,
cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER!,
useTLS: true,
})
ts
// app/api/notify/route.ts
import { pusherServer } from '@/lib/pusher-server'
import { NextRequest, NextResponse } from 'next/server'
export async function POST(req: NextRequest) {
const body = await req.json()
await pusherServer.trigger(
`channel-${body.roomId}`, // channel
'new-message', // event
{ text: body.text, userId: body.userId }
)
return NextResponse.json({ ok: true })
}
Auth Endpoint (private / presence channels)
ts
// app/api/pusher/auth/route.ts
import { pusherServer } from '@/lib/pusher-server'
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
export async function POST(req: NextRequest) {
const session = await getServerSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const data = await req.formData()
const socketId = data.get('socket_id') as string
const channel = data.get('channel_name') as string
const presenceData = {
user_id: session.user.id,
user_info: { name: session.user.name, avatar: session.user.image },
}
const authResponse = pusherServer.authorizeChannel(socketId, channel, presenceData)
return NextResponse.json(authResponse)
}
Client Hook
ts
// hooks/usePusher.ts
import { useEffect, useRef } from 'react'
import Pusher, { Channel } from 'pusher-js'
let pusherClient: Pusher | null = null
function getPusherClient() {
if (!pusherClient) {
pusherClient = new Pusher(process.env.NEXT_PUBLIC_PUSHER_KEY!, {
cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER!,
authEndpoint: '/api/pusher/auth',
})
}
return pusherClient
}
export function usePusherChannel(
channelName: string,
events: Record<string, (data: unknown) => void>
) {
const channelRef = useRef<Channel | null>(null)
useEffect(() => {
const client = getPusherClient()
const channel = client.subscribe(channelName)
channelRef.current = channel
for (const [event, handler] of Object.entries(events)) {
channel.bind(event, handler)
}
return () => {
for (const event of Object.keys(events)) {
channel.unbind(event)
}
client.unsubscribe(channelName)
}
}, [channelName])
}
Usage
tsx
// components/ChatRoom.tsx
export function ChatRoom({ roomId }: { roomId: string }) {
const [messages, setMessages] = useState<Message[]>([])
usePusherChannel(`presence-room-${roomId}`, {
'new-message': (data) => setMessages((p) => [...p, data as Message]),
})
return <MessageList messages={messages} />
}

5. Ably Setup

Install
bash
npm install ably
Token Auth Endpoint
ts
// app/api/ably/token/route.ts
import Ably from 'ably'
import { NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
const ably = new Ably.Rest(process.env.ABLY_API_KEY!)

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
0

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/dinaf2026-web/awesome-web-skills/web-realtime/badge)](https://verified-skill.com/skills/dinaf2026-web/awesome-web-skills/web-realtime)

Something wrong with this skill or its page? Tell us.