What is eventsource?
EventSource is a web browser feature (part of the Server‑Sent Events standard) that lets a web page open a one‑way connection to a server and receive automatic updates as plain text messages. Think of it as a simple “push” channel where the server can send new data to the browser without the browser having to ask for it each time.
Let's break it down
- Server‑Sent Events (SSE): A protocol that streams text data over an HTTP connection.
- EventSource object: JavaScript code you write in the browser, e.g.,
new EventSource('/stream')
. - Connection: The browser makes a single HTTP request that stays open. The server keeps writing lines like
data: ...\n\n
. - Events: Each block of data becomes an “event” that your JavaScript can listen for (
message
,open
,error
). - One‑way: Data flows from server → client only; the client cannot send data back on the same channel (use fetch/AJAX for that).
Why does it matter?
- Live updates: Perfect for dashboards, notifications, chat messages, stock tickers, or any UI that needs fresh data instantly.
- Less overhead: Unlike repeatedly polling the server, SSE uses a single persistent connection, saving bandwidth and server load.
- Built‑in support: Modern browsers implement EventSource natively, so you don’t need extra libraries for basic use.
- Simple text format: Easy to debug with plain‑text tools; no binary framing like WebSockets.
Where is it used?
- Real‑time news feeds or blog comment streams.
- Monitoring dashboards that show live metrics (CPU usage, sensor data).
- Collaborative apps that push status changes (e.g., “user is typing”).
- Notification systems for web apps (e.g., new email alerts).
- Any situation where the server needs to push occasional updates but a full duplex channel (WebSocket) would be overkill.
Good things about it
- Easy to implement: Server just writes text lines; client uses a few lines of JavaScript.
- Automatic reconnection: Browsers automatically try to reconnect if the connection drops.
- Works over standard HTTP/HTTPS: No special ports or protocols required, so it passes through most firewalls.
- Graceful fallback: If a browser doesn’t support EventSource, you can fall back to long‑polling.
- Low latency: Updates arrive as soon as the server sends them, typically within milliseconds.
Not-so-good things
- One‑way only: Cannot send data back on the same channel; you need separate requests for client‑to‑server communication.
- Limited to text: Binary data must be base64‑encoded, which adds overhead.
- Browser support: Older browsers (e.g., Internet Explorer) lack native EventSource, requiring polyfills.
- Scalability concerns: Keeping many long‑lived HTTP connections open can strain servers if not managed properly (needs proper connection handling or a dedicated SSE server).
- No built‑in message ordering guarantees if the network drops and reconnects; you may receive duplicate or out‑of‑order events and must handle that in your code.