What are server-sent events?
Server-Sent Events (SSE) is a web technology that allows a server to send real-time updates to a browser over a single HTTP connection. Unlike WebSockets, SSE is unidirectional, meaning data flows only from the server to the client.
Key Features of SSE
-
Unidirectional Communication:
- The server can push updates to the client, but the client cannot send data back through the same connection.
-
Uses HTTP Protocol:
- SSE operates over standard HTTP, making it easier to implement with existing infrastructure like firewalls and load balancers.
-
Persistent Connection:
- Maintains a single long-lived connection between the client and server.
-
Automatic Reconnection:
- The browser automatically attempts to reconnect if the connection is lost.
-
Simple API:
- SSE uses the
EventSource
API for easy implementation.
- SSE uses the
How SSE Works
-
Server Setup:
- The server sends data in text/event-stream format with a
Content-Type
header oftext/event-stream
. - The server keeps the connection open and streams updates to the client.
- The server sends data in text/event-stream format with a
-
Client Setup:
- The client uses the
EventSource
object to listen for messages.
- The client uses the
Example
Server-Side (Node.js Example)
const http = require('http');
http
.createServer((req, res) => {
if (req.url === '/events') {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
});
setInterval(() => {
res.write(`data: ${new Date().toISOString()}\n\n`);
}, 1000);
}
})
.listen(3000, () => console.log('Server running on port 3000'));
Client-Side
const eventSource = new EventSource('/events');
eventSource.onmessage = (event) => {
console.log('Message from server:', event.data);
};
eventSource.onerror = () => {
console.error('Connection error');
};
Advantages of SSE
-
Ease of Use:
- Simple API and no need for additional libraries.
-
Automatic Reconnection:
- The client automatically reconnects if the connection drops.
-
Built-In Message Handling:
- Supports event-specific listeners using
addEventListener
.
- Supports event-specific listeners using
-
Lightweight:
- Minimal overhead compared to WebSockets.
Limitations of SSE
-
Unidirectional:
- Only allows data flow from server to client.
-
Limited Browser Support:
- Not supported by Internet Explorer.
-
Scalability Concerns:
- Maintaining many open connections can strain the server.
-
Text-Only Data:
- SSE supports only text; binary data must be encoded.
When to Use SSE
- Real-time updates like stock prices, notifications, or news feeds.
- Scenarios where data flows only from the server to the client.
- Applications that rely on HTTP/2 or HTTP/1.1 infrastructure.