patternjavascriptTip
Server-Sent Events (SSE) for One-Way Real-Time Push
Viewed 0 times
sseserver-sent eventseventsourcereal-timepushstreaming
Problem
Developers reach for WebSockets when they only need server-to-client push (notifications, live feeds, progress), adding bidirectional complexity they don't need.
Solution
SSE uses plain HTTP, auto-reconnects, and works through proxies. The server sends
text/event-stream and the client uses the EventSource API.// Server (Node.js/Express)
app.get('/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
const send = (data) => res.write(`data: ${JSON.stringify(data)}\n\n`);
const interval = setInterval(() => send({ time: Date.now() }), 1000);
req.on('close', () => clearInterval(interval));
});
// Client
const es = new EventSource('/events');
es.onmessage = (e) => console.log(JSON.parse(e.data));
es.onerror = (e) => console.error('SSE error', e);Why
SSE is simpler than WebSockets for push-only use cases: native reconnection, standard HTTP (works with load balancers and auth headers), and browser support goes back to IE polyfills.
Gotchas
- Browsers limit SSE connections to 6 per origin in HTTP/1.1 — use HTTP/2 to avoid this.
- SSE connections hold an open HTTP response — ensure your proxy/CDN timeout is longer than your heartbeat interval.
- EventSource does not support custom headers — use a cookie or query param for auth.
- Send a heartbeat comment (
: ping\n\n) every 15-30s to prevent proxy timeouts.
Revisions (0)
No revisions yet.