Web Development

WebSockets vs Server-Sent Events: Building Real-Time Features

November 30, 2026 · 12 min read

WebSockets vs Server-Sent Events: Building Real-Time Features

WebSockets vs Server-Sent Events is the first decision when you add real-time features such as live notifications, chat, dashboards, order tracking or streamed AI responses. Both let a server push data to the browser the moment something happens, instead of the browser asking again and again. They work very differently, though, and choosing the wrong one adds complexity you do not need.

The short version: use Server-Sent Events (SSE) when data flows mainly from server to client, and WebSockets when both sides need to send messages constantly with low latency. This guide explains how each works, compares them side by side, and includes runnable Node.js examples of both, plus advice on scaling, security and newer options such as WebTransport.

The Quick Answer

Choose Server-Sent Events forChoose WebSockets for
Notifications and activity feedsChat and messaging
Live scores, prices and dashboardsMultiplayer games
Order, delivery and job progress updatesCollaborative editing and whiteboards
Streaming AI responses token by tokenLive audio or binary data in both directions
Logs and build outputTrading screens that send orders as well as receive prices

When the client sends only occasionally, such as posting a chat message once in a while, SSE for updates plus normal HTTP requests for actions is often simpler than WebSockets.

How Server-Sent Events Work

SSE is part of the HTML standard. The browser opens an ordinary HTTP request, and the server keeps the response open, writing events in a simple text format: lines starting with data:, plus optional id:, event: and retry: fields, with a blank line between events. Because it is plain HTTP, it works with existing load balancers, proxies, authentication cookies and HTTP/2.

The browser's EventSource API handles the client side and reconnects automatically if the connection drops. When it does, it sends a Last-Event-ID header so the server can resume from where the stream stopped. MDN's guide to server-sent events covers the details. This Node.js example needs no packages. It serves an event stream and then reads it back the way a browser would, resuming after event 4:

// sse-demo.mjs - a Server-Sent Events endpoint plus a test client (Node 22+, no packages)
import http from "node:http";

const server = http.createServer((req, res) => {
  if (req.url !== "/events") return res.writeHead(404).end();
  res.writeHead(200, {
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    Connection: "keep-alive",
  });
  // Browsers send Last-Event-ID when they reconnect, so you can resume where the stream stopped.
  let id = Number(req.headers["last-event-id"] ?? 0);
  const stopAt = id + 3;
  res.write("retry: 3000\n\n"); // reconnect after 3 seconds if the connection drops
  const timer = setInterval(() => {
    id += 1;
    res.write(`id: ${id}\nevent: order-status\ndata: ${JSON.stringify({ order: 1042, update: id })}\n\n`);
    if (id === stopAt) { clearInterval(timer); res.end(); }
  }, 100);
  req.on("close", () => clearInterval(timer));
});

server.listen(0, async () => {
  const res = await fetch(`http://localhost:${server.address().port}/events`, { headers: { "Last-Event-ID": "4" } });
  console.log("Content-Type:", res.headers.get("content-type"));
  let buffer = "";
  for await (const chunk of res.body.pipeThrough(new TextDecoderStream())) {
    buffer += chunk;
    let end;
    while ((end = buffer.indexOf("\n\n")) !== -1) {
      const fields = Object.fromEntries(buffer.slice(0, end).split("\n").map((line) => {
        const i = line.indexOf(":");
        return [line.slice(0, i), line.slice(i + 1).trim()];
      }));
      buffer = buffer.slice(end + 2);
      if (fields.data) console.log(`id ${fields.id} ${fields.event}: ${fields.data}`);
    }
  }
  server.close();
});

It prints the text/event-stream content type followed by events 5, 6 and 7, each with its own ID and event name. In the browser, the client side is only a few lines:

// In the browser: EventSource reconnects automatically and sends the last event ID it saw
const source = new EventSource("/events", { withCredentials: true });

source.addEventListener("order-status", (event) => {
  const { order, update } = JSON.parse(event.data);
  document.querySelector("#status").textContent = `Order ${order}: update ${update}`;
});

source.onerror = () => console.warn("Connection lost; the browser will retry automatically");

SSE has three limitations to know. It is one-way, from server to client. It carries text only, so binary data must be encoded. And over HTTP/1.1, browsers allow only about six connections per domain, which SSE tabs can use up; HTTP/2 and HTTP/3 multiplex many streams over one connection and remove that problem.

How WebSockets Work

A WebSocket starts as an HTTP request with an Upgrade header. If the server agrees, the connection switches to the WebSocket protocol defined in RFC 6455: a persistent, full-duplex channel where either side can send text or binary messages at any time with very little overhead per message. MDN's WebSockets API guide covers the browser side.

That flexibility comes with more work. There is no automatic reconnection, no built-in message IDs for resuming, and idle connections may be closed by proxies unless you send heartbeats. Most Node.js servers use the ws package, or Socket.IO, which adds reconnection, rooms and fallbacks on top. Browsers and Node.js 22 or later include a WebSocket client. This example runs a tiny chat room and two clients that exchange messages:

// ws-demo.mjs - a two-way chat room: the ws package on the server, the built-in WebSocket client (Node 22+, browsers)
import { WebSocketServer } from "ws";

const wss = new WebSocketServer({ port: 0 });

wss.on("connection", (socket) => {
  socket.on("message", (raw) => {
    const { from, text } = JSON.parse(raw);
    for (const client of wss.clients) {
      if (client !== socket && client.readyState === 1) client.send(JSON.stringify({ from, text })); // 1 = OPEN
    }
  });
});

wss.on("listening", async () => {
  const url = `ws://localhost:${wss.address().port}`;
  const connect = () => new Promise((resolve) => { const ws = new WebSocket(url); ws.onopen = () => resolve(ws); });
  const [amina, ben] = await Promise.all([connect(), connect()]);

  ben.onmessage = ({ data }) => {
    const msg = JSON.parse(data);
    console.log(`Ben got from ${msg.from}: ${msg.text}`);
    ben.send(JSON.stringify({ from: "Ben", text: "Joining now" }));
  };
  amina.onmessage = ({ data }) => {
    const msg = JSON.parse(data);
    console.log(`Amina got from ${msg.from}: ${msg.text}`);
    amina.close(); ben.close(); wss.close();
  };

  amina.send(JSON.stringify({ from: "Amina", text: "Stand-up starts in 5 minutes" }));
});

Ben receives Amina's message and replies, Amina receives the reply, and everything shuts down cleanly. The same server code works with browser clients, because they use the same WebSocket API.

Side-by-Side Comparison

FeatureServer-Sent EventsWebSockets
DirectionServer to clientBoth directions
ProtocolStandard HTTP responseUpgraded connection, ws:// or wss://
DataUTF-8 textText and binary
ReconnectionAutomatic, with resume by event IDYou build it, or use a library
Browser APIEventSourceWebSocket
Proxies and firewallsUsually fine, but watch response bufferingUsually fine; some proxies need configuration
AuthenticationCookies work as normalCookies on the handshake, or a token in the first message
Best forFeeds, notifications and streaming outputInteractive, two-way, low-latency apps

Five Questions to Choose the Right Option

Most WebSockets vs Server-Sent Events decisions come down to five questions:

  1. Who sends most of the messages? If it is almost always the server, start with SSE.
  2. How often does the client send, and how fast must it arrive? Many small client messages per second point to WebSockets.
  3. Do you need binary data? Audio, video frames or compact binary formats favour WebSockets, or WebTransport for media.
  4. What does your hosting support? Check connection time limits and WebSocket support on your platform and CDN.
  5. How much do you want to build? SSE gives you reconnection and resume for free; with WebSockets you add them yourself or use a library.

Worked Example: Live Order Tracking

Imagine a delivery app where customers watch their order move from "confirmed" to "out for delivery". Updates come only from the server, a few times per order, so SSE fits. Give every update an increasing ID and store recent updates per order. When a phone switches from Wi-Fi to mobile data, EventSource reconnects and sends the last ID it saw, and the server replays anything missed. Cancelling the order is a rare client action, so it stays an ordinary POST request to your API.

Now add live chat between customer and driver. Messages flow both ways, need typing indicators and should feel instant, so that part uses WebSockets. Many real products mix both, choosing per feature rather than per app.

Real-Time AI Features

If you have used ChatGPT or Claude, you have seen SSE at work. The major AI APIs stream generated text as server-sent events, and most chat interfaces relay that stream to the browser the same way. For streaming answers from an LLM, SSE is the natural choice. Voice and live audio products are different: they send audio in both directions, so they use WebSockets or WebRTC, as our guide to voice AI agents explains. Heavy client-side processing of streamed data, such as decoding media or running a model in the browser, can also benefit from WebAssembly.

Scaling Real-Time Features

Both technologies hold a connection open for every active user, which changes how you scale compared with normal request and response traffic:

  • Connection capacity: each open connection uses memory and a file descriptor. An event-driven runtime such as Node.js can hold many thousands per server, but plan and load-test for your peak.
  • Fan-out across servers: when you run several instances, a message received on one server must reach users connected to the others. A pub/sub layer such as Redis, NATS or a managed real-time service handles this.
  • Hosting limits: some serverless and edge platforms cap request duration or do not support WebSockets on every plan. Check before you choose; our guide to types of web hosting and our overview of serverless architecture explain the trade-offs.
  • Buffering proxies: reverse proxies such as Nginx may buffer responses, which delays SSE events. Disable buffering for event-stream routes.
  • Heartbeats: send a comment line for SSE, or a ping frame for WebSockets, every 20 to 30 seconds so idle connections are not cut.
  • Backpressure: slow clients can build up queues on the server. Drop or merge updates for clients that cannot keep up.

Choosing a runtime matters too. Bun and Deno include built-in WebSocket servers, as our comparison of Node.js, Bun and Deno explains.

Security Considerations

  • Always encrypt: use HTTPS for SSE and wss:// for WebSockets.
  • Authenticate on connect: EventSource cannot set custom headers, so SSE usually relies on secure session cookies. For WebSockets, authenticate during the handshake or in the first message, and avoid tokens in URLs, which end up in logs. Our guide to JWT vs session authentication explains the options.
  • Check the Origin header: browsers send cookies with WebSocket handshakes, so verify the origin to prevent cross-site WebSocket hijacking.
  • Authorise every message: check that the user may join each room or receive each event, and validate every incoming WebSocket message as you would an API request.
  • Limit abuse: cap message size, message rate and connections per user.

Testing and Debugging Real-Time Connections

Browser developer tools show both protocols: the Network panel lists SSE events in an EventStream tab and WebSocket frames in a Messages tab. From the command line, curl with the -N flag prints an SSE stream as events arrive, which is a quick way to check that a proxy is not buffering. Before launch, load-test with tools such as k6 or Artillery, which can open thousands of concurrent connections, and watch memory, open connections and message delay on your servers. In production, log connection counts, disconnect reasons and reconnect rates, because a spike in reconnects is often the first sign of a proxy timeout or a deploy that dropped connections.

What About Polling, gRPC and WebTransport?

Polling and long polling still work as a fallback and are fine for updates every minute or so. gRPC streaming suits server-to-server communication, as our comparison of REST, GraphQL and gRPC explains, but browsers need a proxy to use it. WebTransport is the newest option: built on HTTP/3, it offers multiple streams and unreliable datagrams, which suit games and live media. It became Baseline in March 2026 when Safari 26.4 added support, so it now works in all major browsers. See MDN's WebTransport API guide. Server support is still maturing, so for most business apps SSE and WebSockets remain the practical choices. For ordinary request-response endpoints alongside your real-time features, see our Node.js REST API tutorial.

Frequently Asked Questions

Is SSE better than WebSockets?

Neither is better in general. SSE is simpler and better for one-way streams from server to client. WebSockets are better when both sides send frequent messages with low latency.

Can Server-Sent Events send data from the client to the server?

No. SSE is one-way. Clients send data with normal HTTP requests, such as fetch calls to an API, which works well when client messages are occasional.

Do Server-Sent Events work with HTTP/2?

Yes, and they work better. HTTP/2 multiplexes many streams over one connection, which removes the HTTP/1.1 limit of about six connections per domain.

Are WebSockets supported by all browsers?

Yes. All modern browsers support WebSockets and EventSource, and Node.js 22 and later include a built-in WebSocket client.

Should I use Socket.IO or plain WebSockets?

Socket.IO adds reconnection, rooms, acknowledgements and fallbacks, which saves time for chat-style apps. Plain WebSockets with the ws package are lighter and avoid a custom protocol, but you build those features yourself.

How do ChatGPT-style apps stream responses?

Most stream tokens from the AI API as server-sent events and pass them on to the browser over SSE or a streamed HTTP response, which displays the text as it arrives.

Build Real-Time Features That Scale

We build real-time features such as live dashboards, chat, notifications and streamed AI interfaces, with the right protocol, hosting and security for your traffic. Contact our team to discuss your real-time project.

Want this built for you?

Our team offers Website Deploy On Vercel — get a free quote.

View Services