What is Server-Sent Events (SSE)?
Server-Sent Events (SSE) is a web technology that enables servers to push real-time updates to clients over HTTP. Unlike WebSockets, SSE is unidirectional, meaning data flows only from server to client.
How It Works
The client establishes a persistent connection using the EventSource API:
javascript
const eventSource = new EventSource('/events');
eventSource.onmessage = (event) => {
console.log(event.data);
};
The server keeps the connection open and sends events in this format:
data: {"message": "Update"}
Key Features
- Automatic reconnection
- Event types support
- Native browser support
- Works over HTTP/HTTPS
- Simpler than WebSockets
- Built-in error handling
Use Cases
- Live feed updates
- Status updates
- Real-time notifications
- Progress indicators
- Stock tickers
Browser Support
SSE is supported in all modern browsers, with polyfills available for older ones.
Limitations
- Maximum number of concurrent connections
- One-way communication only
- Potential proxy issues
Best Practices
- Include retry mechanism
- Handle connection errors
- Monitor connection state
- Clean up on page unload