Detailed Explanation of SSE (Server-Sent Events)
๐ง What is SSE?
SSE (Server-Sent Events) is a communication mechanism defined in the HTML5 standard that allows the server to actively push events to the client (browser). Unlike traditional HTTP request-response, SSE is a unidirectional streaming communication protocol based on HTTP.
๐ Core Features
| Feature |
Description |
| Communication Method |
Unidirectional: Server โ Client |
| Connection Type |
Persistent HTTP Long Connection |
| Data Format |
Text (MIME type:<span>text/event-stream</span>) |
| Automatic Reconnection |
Automatically supported by the browser |
| Underlying Protocol |
HTTP/1.1, compatible with HTTP proxies, caching, and authentication |
| Establishment Method |
On the client side, using the <span>EventSource</span> object |
๐งฑ Communication Process (Architecture Diagram)
Browser (Client)
โโโ Initiates HTTP GET request (Accept: text/event-stream)
โ
Server (maintains connection)
โโโ Whenever there is an event, push:
data: xxx
id: 1
event: myEvent
retry: 3000
[Connection remains open, server continues to send, client continues to receive]
๐งช Example Explanation
1. Client (JS)
const source = new EventSource('/events');
source.onmessage = (event) => {
console.log('Default message:', event.data);
};
source.addEventListener('update', (event) => {
console.log('Received update event:', event.data);
});
source.onerror = (err) => {
console.error('Connection error', err);
};
2. Server (Node.js Example)
app.get('/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.write('retry: 5000\n'); // Automatic reconnection time
res.write('event: update\n');
res.write(`data: Hello, client\n\n`);
const interval = setInterval(() => {
res.write(`data: Current time ${new Date().toISOString()}\n\n`);
}, 3000);
req.on('close', () => {
clearInterval(interval);
res.end();
});
});
๐ฏ Typical Application Scenarios
| Scenario |
Description |
| Real-time Notification System |
Message pushing, task progress reminders |
| Real-time Monitoring Dashboard |
Logs, CPU, memory, API status |
| Data Display Screen |
Stock/weather/news stream updates |
| Chat Room (Read-only) |
Only requires server to broadcast messages |
| DevTools/Log Monitoring |
Real-time display of build logs |
๐ SSE Message Format
event: update
id: 12345
retry: 5000
data: Hello
data: World
Field Description
| Field |
Description |
<span>data:</span> |
Message content, can be multiple lines, concatenated by the client into one |
<span>event:</span> |
Event name, used with JS’s <span>addEventListener</span> |
<span>id:</span> |
Message ID, automatically cached by the client for reconnection |
<span>retry:</span> |
Tells the browser the next reconnection time (ms) |
๐งฐ Comparison with WebSocket
| Comparison Item |
SSE |
WebSocket |
| Communication Direction |
Unidirectional (Server โ Client) |
Bidirectional |
| Protocol |
Based on HTTP |
Uses ws:// or wss:// (non-HTTP) |
| Complexity of Use |
Simple (natively supported by the browser) |
Requires manual management of message format and connection state |
| Data Format |
Plain text (<span>text/event-stream</span>) |
| Automatic Reconnection |
Natively supported by the browser |
Needs to be implemented manually |
| Proxy Support |
Good (HTTP proxy available) |
Poor (many HTTP proxies do not support) |
| Application Scenarios |
Real-time notifications, log streams |
Chat, games, collaborative operations, and other frequently interactive scenarios |
๐ก Browser Support
| Browser |
Support Status |
| Chrome |
โ
|
| Firefox |
โ
|
| Safari |
โ
|
| Edge (Chromium) |
โ
|
| Internet Explorer |
โ Not supported |
| Mobile Browsers |
โ
(most modern browsers) |
โ ๏ธ Limitations and Considerations
- Not supported in IE
- Can only push from the server
- Limited by HTTP connection count
- Not suitable for transmitting large binary data
๐ Cross-Origin & Authentication
- Use CORS for cross-origin support:
Access-Control-Allow-Origin: *
Content-Type: text/event-stream
new EventSource(`/events?token=abc123`);
๐ฆ Framework and Tool Support
| Technology Stack |
Support Method |
| Node.js |
Native, Express, NestJS |
| Python |
Flask + <span>flask-sse</span>, Django Channels |
| Java |
Spring WebFlux, Servlet Push |
| Go |
Native <span>net/http</span> |
| Rust |
Actix, Rocket support SSE |
| Vue/React |
Wrap <span>EventSource</span> in Hook/Composables |
| Nginx |
Can proxy SSE, needs to disable caching, configure <span>proxy_buffering off;</span> |
โ
Summary: Advantages and Application Judgments of SSE
- โ
Simple, lightweight, easy to implement and deploy (based on HTTP)
- โ
Suitable for real-time monitoring, system notifications, data stream updates
- โ Not suitable for scenarios requiring client to send messages or binary transmission
- โ Compatibility issues need to consider IE or enterprise intranet browser situations