Server-Sent Events (SSE)0%

Server-Sent Events (SSE)

Beginner12 min read•Updated: Jul 11, 2026
Study Materials

Server-Sent Events (SSE) in Modern JavaScript

While WebSockets excel at bidirectional communication, many real-world applications only need unidirectional updates from the server to the client—such as real-time stock quotes, AI streaming text responses (like ChatGPT / LLMs), live sports scores, and social notifications. Server-Sent Events (SSE) provide a lightweight, HTTP-based streaming protocol with built-in reconnection.


1. SSE vs. WebSockets

FeatureServer-Sent Events (SSE)WebSockets
DirectionUnidirectional (Server -> Client only)Bidirectional (Full Duplex)
ProtocolStandard HTTP / HTTPSCustom WS / WSS protocol
HTTP/2 MultiplexingFully supported out of the boxRequires separate TCP connection
Automatic ReconnectionBuilt-in natively by the browserMust be coded manually
Firewall / Proxy FriendlyPasses standard HTTP proxies easilySometimes blocked by corporate proxies
Data FormatUTF-8 text streams (often JSON)Text and Binary (Blob, ArrayBuffer)

2. The EventSource Client API

Consuming an SSE stream in JavaScript requires just a few lines using the native EventSource API:

JavaScript
// Connect to SSE stream endpoint over standard HTTPS
const eventSource = new EventSource('/api/v1/live-feed');
 
// 1. Connection Opened
eventSource.onopen = () => {
console.log('[SSE] Streaming connection established.');
};
 
// 2. Default Message Handler
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('[SSE] Default update received:', data);
};
 
// 3. Named Custom Events (Dispatched by server 'event: update_stock')
eventSource.addEventListener('stock_tick', (event) => {
const stock = JSON.parse(event.data);
console.log(`Stock ${stock.ticker} updated: $${stock.price}`);
});
 
// 4. Error Handling (Browser auto-reconnects automatically!)
eventSource.onerror = (err) => {
if (eventSource.readyState === EventSource.CLOSED) {
console.log('[SSE] Connection closed by server.');
} else {
console.warn('[SSE] Connection interrupted. Browser will auto-reconnect.');
}
};
 
// Close connection manually:
// eventSource.close();

3. Server-Side Protocol Format

SSE operates over standard HTTP with headers:

  • Content-Type: text/event-stream
  • Cache-Control: no-cache
  • Connection: keep-alive

The Raw Wire Format:

HTTP
event: stock_tick
id: 10492
data: {"ticker": "NVDA", "price": 138.50}
 
event: stock_tick
id: 10493
data: {"ticker": "AAPL", "price": 225.10}
 
  • data: The payload string. Multiple lines are joined with newlines.
  • id: The message sequence ID. If connection drops, the browser sends Last-Event-ID: 10493 upon reconnecting so the server can resume missed messages!
  • event: The event type for addEventListener().
  • Double Newline \n\n: Delimits the end of each message frame.

4. Consuming POST Streams with Fetch (AI LLM Streaming)

Standard EventSource only supports GET requests without custom authorization headers. For AI chat completions (POST requests sending message history), stream using the Fetch API with ReadableStream:

JavaScript
async function streamAiResponse(prompt) {
const response = await fetch('/api/chat/stream', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_TOKEN'
},
body: JSON.stringify({ prompt })
});
 
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
 
while (true) {
const { value, done } = await reader.read();
if (done) break;
 
const chunk = decoder.decode(value);
// Append incoming token text to UI in real-time!
processStreamingChunk(chunk);
}
}

Interactive Quiz

Practice Quiz

Question 1
What is the primary communication direction supported by Server-Sent Events (SSE)?
Question 2
What browser API is used natively to consume Server-Sent Events?
Question 3
What happens if an SSE connection is dropped due to temporary network failure?
Question 4
What HTTP Content-Type header must the server send for Server-Sent Events?
Question 5
When is Server-Sent Events preferred over WebSockets?
Next Lesson

Fetch Interceptors & Request Middleware

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext