When learning about real-time updates on the web, one of the first confusing crossroads we encounter is: Should we use Server-Sent Events (SSE) or WebSockets? ๐ค
And then, if we go with SSE, why do articles on MDN keep mentioning HTTP/1.1 vs HTTP/2?
Letโs break it down step by step in a beginner-friendly way, focusing on the parts that usually feel tricky. Weโll also look at the headers involved, some code snippets, and use cases to make things concrete.
๐๏ธ SSE vs ๐ด WebSockets (The Big Picture)
Both SSE and WebSockets allow servers to push updates to the client without the client repeatedly asking. But the way they do it is different:
-
๐ก SSE (Server-Sent Events):
- Works over regular HTTP ๐
- Server can keep sending messages (events) to the client whenever it wants
- One-way only โก๏ธ server โ client
- Very simple API in browsers (
EventSource
)
-
๐ WebSockets:
- Creates a special persistent connection (not plain HTTP)
- Allows two-way communication (client โ server)
- More powerful ๐ช but also more complex ๐งฉ
๐ Think of SSE as a radio broadcast ๐ป (server speaks, clients listen), while WebSockets are more like a phone call โ๏ธ (both can talk).
๐จ Headers and Handshakes
This is one of the confusing parts: how do the two approaches actually start communication?
๐น SSE Headers
Client Request (Browser โ Server):
GET /events HTTP/1.1
Accept: text/event-stream
Cache-Control: no-cache
Connection: keep-alive
Server Response (Server โ Browser):
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive
data: Hello Client!\n\n
data: Another message\n\n
๐ The key here is text/event-stream
. The server keeps the connection open and streams events continuously ๐.
๐น WebSocket Headers
Client Request (Browser โ Server):
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Server Response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
๐ Notice how WebSockets use Upgrade: websocket
. This โswitchesโ the connection from HTTP into the WebSocket protocol ๐๐.
๐ป Code Snippets
Client-side SSE Example
const eventSource = new EventSource('/events');
// Listen for messages
eventSource.onmessage = function(event) {
console.log('๐จ New event:', event.data);
};
// Optional: custom events
eventSource.addEventListener('update', (event) => {
console.log('๐ Update received:', event.data);
});
Server-side SSE (Node.js Example)
const http = require('http');
http.createServer((req, res) => {
if (req.url === '/events') {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
setInterval(() => {
res.write(`data: ${new Date().toISOString()}\n\n`);
}, 1000);
}
}).listen(3000);
Client-side WebSocket Example
const socket = new WebSocket('ws://localhost:3000');
socket.onopen = () => {
console.log('โ
Connected to server');
socket.send('๐ Hello from client');
};
socket.onmessage = (event) => {
console.log('๐จ Received:', event.data);
};
Server-side WebSocket Example (Node.js + ws)
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3000 });
wss.on('connection', (ws) => {
ws.on('message', (message) => {
console.log('๐ฅ Received:', message);
ws.send(`Echo: ${message}`);
});
ws.send('๐ Welcome to WebSocket server!');
});
๐ The Role of HTTP/1.1 vs HTTP/2
This is where most people get tripped up ๐ . SSE is built on top of HTTP. That means how well it works depends on the version of HTTP being used.
๐ HTTP/1.1
- Browsers limit connections to about 6 per domain ๐
- Each SSE connection keeps one connection โopenโ for streaming
- After 6 open SSE streams, any new requests (even a normal GET for an image or CSS) might get queued โณ
[Client] ---SSE Stream 1---> [Server]
[Client] ---SSE Stream 2---> [Server]
...
[Limit reached ๐ง: other requests wait in line]
๐ HTTP/2
- Uses multiplexing ๐: many streams can share a single connection
- Default is 128 concurrent streams per connection (can be configured)
- SSE works much better, since each new stream is just another logical channel inside one TCP connection
[Client] == Stream 1 ==>
== Stream 2 ==>
== Stream 3 ==> [Server]
(All on the same connection ๐, no blocking)
๐ฏ When to Use SSE
- ๐ฐ Live news feeds or stock tickers
- ๐ Notifications
- ๐ค Collaborative tools where clients mostly listen
๐ Use SSE if:
- You only need one-way communication
- You want something simple to set up
- Your server already works with HTTP
๐ฎ When to Use WebSockets
- ๐ฌ Chat apps
- ๐น๏ธ Online games
- โ๏ธ Collaborative editing (like Google Docs)
๐ Use WebSockets if:
- You need real-time, two-way data flow
- You expect high-frequency messages โก
- Youโre okay with a bit more setup complexity
โ Why This Matters
Many think โreal-time = WebSockets alwaysโ ๐ซ. But thatโs not true.
SSE is often enough for things like notifications, live scores, or stock prices. And with HTTP/2, it becomes super efficient ๐.
โ Remember:
- SSE = simpler and runs on normal HTTP
- WebSockets = more flexible but more complex
- HTTP/2 makes SSE shine โจ
๐ Also Read:
FreeCodeCamp โ SSE vs WebSockets
๐ก Tip: Start with SSE if your use case fits. Only move to WebSockets when you really need two-way real-time communication.
Top comments (0)