In the previous article, we understood why Server-Sent Events (SSE) exist.
Now letβs go deeper:
π How does SSE actually work under the hood?
βοΈ Step 1 β It Starts with a Normal HTTP Request
From the browserβs perspective, SSE begins like any other request:
GET /events
But the server responds differently.
π‘ Step 2 β Special Response Header
The server sends:
Content-Type: text/event-stream
This header tells the browser:
βThis response is not going to end. Keep listening.β
π Step 3 β The Connection Stays Open
Unlike normal APIs:
Client β request β response β close
SSE does this:
Client β request
Server β response (never ends)
π§ Mental Model
Think of it like opening a tap:
Client β open connection
Server β stream data continuously
Instead of sending a bucket of water, the server sends a flow.
π¦ Step 4 β Event Format
SSE sends data in a very specific format.
Example:
data: Order received
data: Cooking started
data: Out for delivery
Important Rules:
- Each message starts with
data: - Each event ends with a blank line
- Without the blank line, the browser keeps waiting
π§© Multiple Lines in One Event
data: hello
data: world
This becomes a single message:
hello
world
π·οΈ Advanced Event Format
SSE supports more fields:
id: 101
event: order_update
data: cooking started
Fields Explained:
-
dataβ actual message -
eventβ custom event type -
idβ event identifier (used for reconnection)
π Browser Support
Browsers provide a built-in API:
π EventSource
Example:
const source = new EventSource("/events")
source.onmessage = (event) => {
console.log(event.data)
}
π― Custom Event Handling
If the server sends:
event: order
data: shipped
You can listen like this:
source.addEventListener("order", (event) => {
console.log(event.data)
})
π Automatic Reconnection
One of the most powerful features of SSE:
π The browser automatically reconnects if the connection drops.
Even better, it sends:
Last-Event-ID: 101
So the server can resume from where it left off.
π§ Why SSE Is Simple
SSE works because it:
- Uses standard HTTP
- Requires no protocol upgrade
- Has built-in browser support
- Handles reconnection automatically
Compared to WebSocket, it is much simpler to implement.
β οΈ Common Mistake
A very common bug:
Forgetting the blank line at the end of an event.
data: hello
This will not work properly.
Correct version:
data: hello
π Whatβs Next
In the next article, weβll answer a very important question:
π When should you use SSE vs Polling vs WebSockets?
This is one of the most common interview questions β and also a critical design decision in real systems.
Top comments (0)