DEV Community

Cover image for Understanding Server-Sent Events (SSE) and Why HTTP/2 Matters
Abhinav
Abhinav

Posted on

Understanding Server-Sent Events (SSE) and Why HTTP/2 Matters

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ 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
Enter fullscreen mode Exit fullscreen mode

Server Response:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ 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);
});
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
};
Enter fullscreen mode Exit fullscreen mode

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!');
});
Enter fullscreen mode Exit fullscreen mode

๐ŸŒ 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]
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ˆ 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)
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฏ 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)