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.
| 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) |
Consuming an SSE stream in JavaScript requires just a few lines using the native EventSource API:
SSE operates over standard HTTP with headers:
Content-Type: text/event-streamCache-Control: no-cacheConnection: keep-alivedata: 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().\n\n: Delimits the end of each message frame.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:
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| WebSockets for Real-Time Bidirectional Communication | Fetch Interceptors & Request Middleware |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.