InterviewHubPRO
Section Overview
Q61

Question 61 of 521

Part 2: Promises, Callbacks, Async & Strict Mode (54 - 103)

12%
JavaScript Internals (521 Qs)•Part 2: Promises, Callbacks, Async & Strict Mode (54 - 103)

What are server-sent events

Server-sent events (SSE) is a server push technology enabling a browser to receive automatic updates from a server via HTTP connection without resorting to polling. These are a one way communications channel - events flow from server to client only. This has been used in Facebook/Twitter/X updates, stock price updates, news feeds etc.

Practical Code Example

javascript
// Server-Sent Events (SSE): Unidirectional real-time stream from server to client
const eventSource = new EventSource('/api/live-stock-prices');

eventSource.onopen = () => console.log('SSE connection established');

eventSource.onmessage = (event) => {
  const stock = JSON.parse(event.data);
  console.log('Live price update:', stock.symbol, stock.price);
};

eventSource.onerror = (err) => {
  console.error('SSE Error or server reconnecting:', err);
};