Server-Sent Events (SSE)
Unidirectional communication protocol enabling servers to push real-time updates to clients over HTTP.
Updated on January 7, 2026
Server-Sent Events (SSE) is a standardized web technology that establishes a persistent HTTP connection allowing servers to automatically send updates to clients. Unlike bidirectional WebSockets, SSE uses unidirectional communication optimized for server-to-browser data streams. This browser-native approach significantly simplifies implementing real-time features like notifications, dynamic dashboards, or news feeds.
Fundamentals
- HTTP-based protocol with automatic reconnection on disconnection
- Simple text data format using 'text/event-stream' MIME type
- Native JavaScript EventSource API integrated in all modern browsers
- Built-in support for event IDs to resume after interruption
Benefits
- Implementation simplicity compared to WebSockets for unidirectional use cases
- Native automatic reconnection without additional client-side code
- Compatible with existing HTTP infrastructure (proxies, load balancers, CDN)
- No special network configuration or non-standard ports required
- Native ID management to resume interrupted streams without data loss
Practical Example
// Node.js server with Express
import express from 'express';
const app = express();
app.get('/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.setHeader('Access-Control-Allow-Origin', '*');
// Send initial event
res.write('data: {"message": "Connection established"}\n\n');
// Periodic data sending
const intervalId = setInterval(() => {
const data = {
timestamp: new Date().toISOString(),
value: Math.random() * 100
};
res.write(`id: ${Date.now()}\n`);
res.write(`event: update\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
}, 2000);
// Cleanup on disconnection
req.on('close', () => {
clearInterval(intervalId);
res.end();
});
});
app.listen(3000);// TypeScript client
const eventSource = new EventSource('http://localhost:3000/events');
// Listen to custom events
eventSource.addEventListener('update', (event: MessageEvent) => {
const data = JSON.parse(event.data);
console.log('Update received:', data);
updateDashboard(data);
});
// Error handling and reconnection
eventSource.onerror = (error) => {
console.error('SSE error:', error);
if (eventSource.readyState === EventSource.CLOSED) {
console.log('Connection closed, auto-reconnecting...');
}
};
// Listen to all messages
eventSource.onmessage = (event: MessageEvent) => {
console.log('Generic message:', event.data);
};
// Manual close if needed
function cleanup() {
eventSource.close();
}Implementation
- Configure an HTTP endpoint that keeps the connection open with appropriate headers
- Implement the text/event-stream format with data, event, id, and retry fields
- Client-side, instantiate EventSource with the SSE endpoint URL
- Define event listeners to process received real-time data
- Implement error handling and define custom reconnection strategy if needed
- Optimize performance by limiting send frequency and compressing data
- Test resilience with network interruptions and validate resumption with event IDs
Pro tip
Use SSE instead of WebSockets when communication is primarily unidirectional (server → client). SSE consumes fewer server resources, traverses corporate proxies better, and benefits from native automatic reconnection. For real-time dashboards, notification streams, or price updates, SSE offers the best simplicity-to-performance ratio. Reserve WebSockets for applications requiring intensive bidirectional communication like chat or multiplayer games.
Related Tools
- Express.js and Fastify for creating SSE endpoints in Node.js servers
- EventSource polyfills like eventsource for Node.js or legacy browsers
- NGINX and Apache with proxy_buffering off configuration for SSE
- Redis Pub/Sub to distribute events across multiple server instances
- React Query or SWR to integrate SSE in modern React applications
- Mercure for a standardized SSE protocol with authentication and authorization
Server-Sent Events represents an elegant and performant solution for applications requiring unidirectional real-time updates. Its implementation simplicity, native browser integration, and compatibility with standard HTTP infrastructure make it a strategic choice to reduce technical complexity while delivering responsive user experiences. In contexts where development velocity and reliability are crucial, SSE enables delivering real-time features with minimal investment and simplified maintenance.
