When to Use SSE vs WebSocket vs Polling: A Practical Node.js Guide

This article explains the three common server‑to‑client push techniques—polling, WebSocket and Server‑Sent Events (SSE)—detailing their principles, advantages, drawbacks, browser compatibility, key APIs, and provides a complete Node.js/Express demo with front‑end code to help developers choose the right solution for real‑time data scenarios.

Top Architect
Top Architect
Top Architect
When to Use SSE vs WebSocket vs Polling: A Practical Node.js Guide

Introduction

In many web applications the server needs to push data to the client, such as real‑time dashboards, unread‑message notifications, or chat messages. This article introduces the usage scenarios of Server‑Sent Events (SSE) and shows how to implement them.

Server‑to‑client push implementations

Polling

WebSocket

SSE

Polling overview

Polling was historically used to simulate push by repeatedly sending HTTP requests from the client. It is considered a pseudo‑push because the client initiates every request.

Drawbacks of polling:

Each request incurs the full HTTP handshake (TCP three‑way handshake, four‑way termination), causing unnecessary overhead.

The browser must keep sending requests for the entire page lifetime, which is unfriendly to the client.

Browsers limit concurrent connections per domain (e.g., Chrome allows only 6), and long‑running polls can occupy these slots.

Long intervals may lead to delayed data delivery.

WebSocket overview

WebSocket is a full‑duplex protocol that allows bidirectional communication between client and server, making it powerful for scenarios like chat.

Its drawbacks include the need for browsers to support the new ws/wss protocol and a more complex implementation compared to SSE.

Browser compatibility (WebSocket):

SSE overview

SSE is a one‑way communication protocol built on a persistent HTTP/1.1 connection. The server can push data to the client, but the client cannot send messages back.

Long connections are a persistent HTTP/1.1 technique that allows multiple requests/responses over a single TCP connection, reducing server load and improving performance.

Advantages of SSE:

Lightweight compared to WebSocket.

Uses standard HTTP, so existing servers support it without extra configuration.

Lower client resource consumption.

Note: Internet Explorer does not support SSE.

SSE browser compatibility:

Compatibility refers to browsers, not server software.

SSE API and connection states

Creating an SSE connection: var source = new EventSource(url); source.readyState values:

0 – EventSource.CONNECTING: connection not yet established or has been lost.

1 – EventSource.OPEN: connection is open and data can be received.

2 – EventSource.CLOSED: connection closed and will not reconnect.

SSE related events

open : triggered when the connection is established.

message : triggered when data arrives.

error : triggered on communication errors (e.g., connection loss).

Data format

Content-Type: text/event-stream // response format
Cache-Control: no-cache      // do not cache
Connection: keep-alive        // keep the long‑lived connection

Reference documentation: https://www.w3cschool.cn/nwfchn/wpi3cozt.html

Demo implementation

Frontend code (plain HTML)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>SSE Demo</title>
</head>
<body>
  <ul id="ul"></ul>
  <script>
    // generate li element
    function createLi(data) {
      const li = document.createElement("li");
      li.innerHTML = String(data.message);
      return li;
    }
    // check SSE support
    let source = '';
    if (window.EventSource) {
      source = new EventSource('http://localhost:8088/sse/');
    } else {
      throw new Error("Current browser does not support SSE");
    }
    // connection opened
    source.onopen = function(event) {
      console.log(source.readyState);
      console.log("Long connection opened");
    };
    // receive message
    source.onmessage = function(event) {
      console.log(JSON.parse(event.data));
      console.log("Received long‑connection data");
      const li = createLi(JSON.parse(event.data));
      document.getElementById("ul").appendChild(li);
    };
    // connection error
    source.onerror = function(event) {
      console.log(source.readyState);
      console.log("Long connection interrupted");
    };
  </script>
</body>
</html>

Backend code (Node.js + Express)

const express = require('express');
const app = express();
const port = 8088;
// enable CORS
app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Credentials', true);
  if (req.method == 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
});
app.get('/sse', (req, res) => {
  res.set({
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  });
  console.log('Entered long‑connection');
  setInterval(() => {
    const data = { message: `Current time is ${new Date().toLocaleTimeString()}` };
    res.write(`data: ${JSON.stringify(data)}

`);
  }, 1000);
});
app.listen(port, () => {
  console.log(`Server started – http://localhost:${port}`);
});

Result

Conclusion

SSE is lighter than WebSocket.

SSE works over standard HTTP/HTTPS, requiring no extra server support.

WebSocket is a newer ws/wss protocol.

Use SSE when only the server needs to push data (e.g., dashboards, notification centers).

Choose WebSocket for bidirectional communication such as chat.

Both SSE and WebSocket have good browser compatibility; polling should be avoided except for extreme fallback cases.

Internet Explorer does not support SSE; mini‑programs also lack SSE support.

backend developmentNode.jsWebSocketExpressserver-sent-eventsPollingSSE
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.