Skip to main content
Admin Panel
SC
Published
1 min read
230 words
Save
Publish
## WebSockets vs Server-Sent Events WebSockets are bidirectional — great for chat apps. But most dashboards only need server-to-client updates. That's exactly what Server-Sent Events (SSE) provide, with less complexity. | Feature | WebSocket | SSE | |---------|-----------|-----| | Direction | Bidirectional | Server → Client | | Reconnection | Manual | Automatic | | Protocol | ws:// | http:// | | Complexity | High | Low | ## Setting Up SSE in Next.js ```typescript // app/api/events/route.ts export async function GET() { const encoder = new TextEncoder() const stream = new ReadableStream({ start(controller) { const interval = setInterval(() => { const data = JSON.stringify({ visitors: Math.floor(Math.random() * 1000), timestamp: new Date().toISOString(), }) controller.enqueue(encoder.encode(`data: ${data}\n\n`)) }, 1000) return () => clearInterval(interval) }, }) return new Response(stream, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive", }, }) } ``` ## Client-Side Consumption ```tsx "use client" import { useEffect, useState } from "react" export function LiveMetrics() { const [data, setData] = useState<MetricData | null>(null) useEffect(() => { const source = new EventSource("/api/events") source.onmessage = (e) => setData(JSON.parse(e.data)) return () => source.close() }, []) return <MetricCard value={data?.visitors ?? 0} /> } ``` > **Tip:** EventSource automatically reconnects on network failures — no manual retry logic needed. ## Production Considerations - Use a message broker (Redis pub/sub) for multi-instance deployments - Set appropriate timeouts to prevent resource leaks - Implement backpressure for high-frequency updates