Server-Sent Events (SSE) for Real-Time Streaming
Server-Sent Events (SSE) for Real-Time Streaming
While WebSockets provide bidirectional communication, many real-time features are strictly unidirectional—data flows exclusively from server to client. Examples include generative AI LLM token streaming (ChatGPT / Gemini style responses), live stock tickers, server metric telemetry, and build progress notifications. Server-Sent Events (SSE) uses native HTTP to stream text events efficiently with less architectural overhead than WebSockets.
1. WebSockets vs Server-Sent Events (SSE)
| Feature | WebSockets | Server-Sent Events (SSE) |
|---|---|---|
| Directionality | Full-duplex (Bidirectional) | Half-duplex (Server to Client only) |
| Protocol | Custom WS / WSS protocol | Standard HTTP / HTTPS |
| HTTP/2 Support | Limited / Complex multiplexing | Native HTTP/2 multiplexing (efficient) |
| Reconnection | Must be coded manually | Native automatic reconnection built into browser |
| Firewall / Proxy Traversals | Often inspected or blocked | Behaves like standard HTTP stream |
| Client API | new WebSocket() | Native new EventSource() or fetch ReadableStream |
2. Using Native EventSource
The browser's native EventSource interface handles automatic reconnection and event parsing:
3. Streaming AI LLM Responses via fetch ReadableStream
While EventSource is simple, it only supports GET requests and cannot pass custom request body payloads or Authorization headers. For streaming AI completions (which require POST with JSON bodies), consume the response ReadableStream via fetch:
Practice Quiz
Building a Collaborative Multi-User Canvas
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| WebSockets Architecture with Socket.io in React | Building a Collaborative Multi-User Canvas |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.