Server-Sent Events (SSE) is a standard that enables servers to push real-time updates to clients over a single HTTP connection. Unlike WebSocket, SSE is unidirectional - only the server can send data.
Server-Sent Events (SSE)
A standard for pushing real-time updates from server to client over HTTP.
SSE vs WebSocket
| Feature | SSE | WebSocket |
|---|---|---|
| Direction | Server to client | Bidirectional |
| Protocol | HTTP | WebSocket |
| Reconnection | Automatic | Manual |
| Browser Support | Native EventSource | Native WebSocket |
| Complexity | Simple | More complex |
When to Use SSE
- Live Feeds: News, social media updates
- Notifications: Real-time alerts
- Progress Updates: File upload, processing status
- Stock Tickers: Price updates
- Log Streaming: Real-time log viewing
Event Format
SSE uses a simple text-based format with event, data, id, and retry fields.
Advantages
- Works over standard HTTP
- Automatic reconnection
- Event ID for resuming streams
- Simple to implement
Code Examples
Node.js SSE Server
app.get("/events", (req, res) => {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
const sendEvent = (data) => {
res.write(`data: ${JSON.stringify(data)}\n\n`);
};
const interval = setInterval(() => {
sendEvent({ time: new Date().toISOString() });
}, 1000);
req.on("close", () => clearInterval(interval));
});Browser EventSource
const source = new EventSource("/events");
source.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("Update:", data);
};
source.onerror = () => console.log("Connection error");Related Terms
Mock Server
A fake server that simulates API responses for testing and development purposes.
Read more
API Testing
The process of verifying that APIs work correctly, securely, and perform well.
Read more
WebSocket
A protocol enabling full-duplex, real-time communication between client and server.
Read more
REST API
An architectural style for building web APIs using HTTP methods and stateless communication.
Read more