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)