Server-Sent Events (SSE)
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
| Feature | Server-Sent Events (SSE) | WebSockets |
|---|---|---|
| Direction | Unidirectional (Server -> Client only) | Bidirectional (Full Duplex) |
| Protocol | Standard HTTP / HTTPS | Custom WS / WSS protocol |
| HTTP/2 Multiplexing | Fully supported out of the box | Requires separate TCP connection |
| Automatic Reconnection | Built-in natively by the browser | Must be coded manually |
| Firewall / Proxy Friendly | Passes standard HTTP proxies easily | Sometimes blocked by corporate proxies |
| Data Format | UTF-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:
3. Server-Side Protocol Format
SSE operates over standard HTTP with headers:
Content-Type: text/event-streamCache-Control: no-cacheConnection: keep-alive
The Raw Wire Format:
data:The payload string. Multiple lines are joined with newlines.id:The message sequence ID. If connection drops, the browser sendsLast-Event-ID: 10493upon reconnecting so the server can resume missed messages!event:The event type foraddEventListener().- 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:
Practice Quiz
Fetch Interceptors & Request Middleware
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| WebSockets for Real-Time Bidirectional Communication | Fetch Interceptors & Request Middleware |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.