Browser APIs & Web APIs
Server-Sent Events (SSE)
Master server-to-client streaming in JavaScript. Learn the EventSource API, handling connection streams, and contrast SSE with WebSockets.
1. Introduction
When an application only needs to receive real-time updates from the server, opening a bi-directional WebSocket connection can be overkill. Server-Sent Events (SSE) provide a unidirectional, text-based data stream from the server to the client over standard HTTP.
2. Why It Matters
SSE is simpler to implement than WebSockets because it runs over standard HTTP/HTTPS, bypassing firewall blocks. Additionally, the browser handles reconnections automatically, making it ideal for push feeds.
3. Real-World Analogy
Think of a News Radio Broadcast Channel:
- WebSocket (Phone Call): An active, two-way phone call. You can talk and listen at the same time.
- Server-Sent Events (Radio Show): You tune your radio receiver (EventSource) to a specific frequency. The radio host broadcasts updates continuously. You listen to the reports as they arrive, but you cannot talk back over the radio channel. If you want to reply, you must use a separate communication method (like sending a standard HTTP POST request).
4. The EventSource API
In the browser, Server-Sent Events are managed using the EventSource constructor:
5. Protocol Details
SSE uses a simple plain-text protocol over standard HTTP:
• Headers: The server must respond with the Content-Type: text/event-stream and Cache-Control: no-cache headers.
• Format: Messages are sent as text blocks separated by double newlines, prefixed with data::
6. Practical Example
This script demonstrates connecting to a feed, updating the UI when updates arrive, and closing the connection when the user navigates away:
7. Common Mistakes
- Trying to send data from the client over EventSource: EventSource is strictly unidirectional (server-to-client). Attempting to call send methods throws errors because no such methods exist. To send data, use standard HTTP POST requests instead.
- Exceeding browser connection limits: When not using HTTP/2, browsers restrict the number of concurrent open connections to the same domain to 6. Having multiple EventSource tabs open can quickly exhaust this limit and block subsequent page loads. Use HTTP/2 to avoid this connection limit.
8. Quick Quiz
Q1: Which event-stream header must be sent by the server to establish an EventSource connection?
A) Content-Type: application/json
B) Content-Type: text/event-stream
Answer: B — The server must set the Content-Type header to text/event-stream to tell the browser to keep the connection open for streaming updates.
9. Scenario-Based Challenge
The Real-Time Notification Toast:
An application displays real-time push alerts. You want to connect to a server-sent stream: /alerts. If the connection is dropped, EventSource automatically tries to reconnect, but you want to alert users that the app is offline during the disconnect period. Write this connection status tracker.
10. Debugging Exercise
Explain why this custom named event listener never triggers:
const source = new EventSource('/stream');
// Objective: listen for price updates source.onmessage = function(e) { console.log('Logged:', e.data); // never triggers when receiving named events! Why? };
View Solution
Diagnosis: The onmessage property only catches generic messages that do not have a custom event name. If the server sends a message prefixed with event: price-update, you must register a listener using addEventListener() matching that exact name.
Fix: Register a listener using addEventListener() matching the event name sent by the server:
source.addEventListener('price-update', (event) => {
console.log('Price Update:', event.data); // Works!
});
11. Interview Questions
🟢 Q1: Compare Server-Sent Events (SSE) and WebSockets in terms of transport protocol and capabilities.
Answer:
• Transport Protocol: WebSockets use a custom TCP-based protocol (ws://) that requires a handshake to upgrade the connection. SSE runs over standard HTTP, making it easier to integrate with existing firewalls and proxies.
• Direction: WebSockets support full-duplex, bi-directional communication. SSE is strictly unidirectional, allowing only the server to push data to the client.
• Reconnections: EventSource handles reconnections automatically out of the box. WebSockets require developers to write custom reconnection logic.
12. Production Considerations
- • Use HTTP/2: Standard HTTP restricts browser connections to 6 concurrent open connections per domain. Always run SSE over HTTP/2, which supports multiplexing, allowing multiple streams to share a single TCP connection.