Skip to content
Tutorials Center
My learning

Topics

Lesson 100 of 156 ยท Browser APIs

Real-Time Data: WebSockets and Server-Sent Events

Push live data to the browser with WebSockets and Server-Sent Events - events, readyState, reconnecting with backoff, heartbeats, and choosing over polling.

fetch() follows a simple rhythm: the browser asks, the server answers, the conversation is over. That's perfect for loading a page of products. It's a poor fit for a chat, a live sports score, a stock ticker, a multiplayer game or a "your build finished" notification. In all of those, the server has news, and it needs a way to tell the browser right away, without waiting to be asked.

Browsers give you two built-in tools for this. WebSockets open a permanent two-way connection: either side can send a message at any moment. Server-Sent Events (SSE) open a one-way stream: the server pushes events, and the browser listens and even reconnects by itself. In this lesson you'll learn both APIs, how to make connections survive real networks (reconnecting with backoff, heartbeats), and how to choose between polling, SSE and WebSockets.

About the live editors. The editors on this site run in a sandbox with no server to connect to, so a real new WebSocket(...) would only fail. The runnable demos use a small mock socket class with the same events and methods, a MessageChannel, and an SSE stream built in memory with new Response(...). The code that talks to a real server is shown read-only; it uses the exact same patterns.

Polling: the approach to beat

Before WebSockets existed, sites faked real-time updates by polling: asking the server "anything new?" every few seconds.

JavaScript
// Short polling: simple, but mostly wasted requests
setInterval(async () => {
  const res = await fetch("/api/notifications?since=" + lastSeen);
  const items = await res.json();
  if (items.length) showNotifications(items);
}, 5000);

Polling is easy and works through any proxy, but it has two costs. Most requests come back empty, which wastes bandwidth and server time. And news can be up to one interval late. Long polling improves this: the server holds each request open until it has something to say (or a timeout passes), and the browser immediately sends a new request after each answer. It's still one HTTP request per message, though, which is what WebSockets and SSE fix.

Polling remains the right choice when updates are rare and a delay is fine: checking for a new app version every ten minutes doesn't need a permanent connection.

The WebSocket API

A WebSocket starts life as an ordinary HTTP request with an Upgrade: websocket header. If the server agrees, the same TCP connection switches protocols and stays open. From then on, both sides exchange messages (text or binary) with only a few bytes of overhead each.

JavaScript
// Read-only: connecting to a real server
const socket = new WebSocket("wss://chat.example.com/rooms/42");

socket.addEventListener("open", () => {
  socket.send(JSON.stringify({ type: "hello", name: "Ana" }));
});

socket.addEventListener("message", (event) => {
  const msg = JSON.parse(event.data); // event.data: a string, Blob or ArrayBuffer
  console.log("received", msg);
});

socket.addEventListener("close", (event) => {
  console.log("closed", event.code, event.reason, event.wasClean);
});

socket.addEventListener("error", () => {
  console.log("something went wrong"); // no details on purpose; close follows
});

// Later: close politely with a code and an optional reason
socket.close(1000, "user left the room");

The essentials:

  • URL scheme. Use wss:// (encrypted, like https://) in production. Plain ws:// is blocked from secure pages and easily tampered with on the network.
  • Four events. open (ready to send), message (data arrived), error (a failure; for security reasons it carries no details) and close (the connection ended; an error is always followed by a close).
  • readyState tells you where the socket is: WebSocket.CONNECTING (0), OPEN (1), CLOSING (2) or CLOSED (3). Calling send() while still connecting throws an InvalidStateError; after closing, sent data is silently discarded.
  • send(data) accepts a string, Blob, ArrayBuffer or typed array. Set socket.binaryType = "arraybuffer" if you'd rather receive binary data as an ArrayBuffer than as a Blob. socket.bufferedAmount shows how many bytes are queued but not yet sent, which is useful for not flooding a slow connection.
  • Close codes. 1000 means a normal close and 1001 that an endpoint is "going away" (a tab closing, a server restarting). 1006 means the connection dropped without a proper close, typically a network failure. Your own code may call close() with 1000 or a value from 3000 to 4999.

Here is the same flow running against a mock socket that echoes messages back, so you can watch the states and events in order:

JS WebSocket lifecycle with a mock socket

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Designing messages

A WebSocket carries raw messages; it has no URLs, methods or status codes like HTTP. You design a small protocol on top. The most common one is JSON objects with a type field, plus an id when you need to match a reply to a request:

JS A tiny JSON protocol over a socket

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The notice message has no handler, so it's reported as unhandled instead of crashing the client. Treat every incoming message as untrusted input: parse it inside try, check its type, and never insert its text with innerHTML (see Security).

Surviving real networks: reconnecting with backoff

Connections drop: phones switch from Wi-Fi to mobile data, laptops sleep, servers restart during deploys. A WebSocket never reconnects by itself. When close fires unexpectedly, you open a new socket.

Don't reconnect instantly in a tight loop. If the server is down, thousands of clients hammering it every few milliseconds will keep it down. Use exponential backoff: wait 0.5 s, then 1 s, 2 s, 4 s and so on up to a cap, and reset the delay after a successful connection. Add jitter (a random part of the delay) so that clients disconnected at the same moment don't all come back at the same moment.

JS Reconnecting with exponential backoff and jitter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The delays here are in milliseconds so the demo finishes quickly. In real apps, start around half a second and cap at about 30 seconds. Two more habits help:

  • Pause while offline. Listen for the window's online event and try again immediately when it fires, instead of waiting out a long delay.
  • Resume, don't restart. After reconnecting, tell the server the last message ID you saw so it can send what you missed. Otherwise the user silently loses messages.

Heartbeats

A connection can also die silently: a router drops it without anyone sending a close frame, and the browser may not notice for minutes. The WebSocket protocol has built-in ping and pong frames, but browsers don't expose them to JavaScript. Most apps therefore add an application-level heartbeat:

JavaScript
// Read-only: client-side heartbeat for a real socket
const HEARTBEAT_MS = 25_000;
let lastSeen = Date.now();

socket.addEventListener("message", (event) => {
  lastSeen = Date.now();
  if (event.data === "pong") return; // heartbeat reply, not app data
  handle(JSON.parse(event.data));
});

const timer = setInterval(() => {
  if (Date.now() - lastSeen > HEARTBEAT_MS * 2) {
    socket.close(4000, "heartbeat timeout"); // triggers your reconnect logic
    return;
  }
  if (socket.readyState === WebSocket.OPEN) socket.send("ping");
}, HEARTBEAT_MS);

socket.addEventListener("close", () => clearInterval(timer));

The regular ping also keeps proxies and load balancers from closing the connection as "idle". An interval of 20โ€“30 seconds suits most infrastructure.

A live demo: two clients through a relay

To see real-time messaging on a page, here are two chat windows. In a real app each would be in a different browser with a WebSocket to a server. In this sandbox, a MessageChannel plays the server: it's a built-in pair of connected ports, and whatever one port posts arrives at the other as a message event, just like a socket.

Two chat clients connected by a MessageChannel

Type in either window and the message appears in the other one instantly. That's the experience a WebSocket gives users across machines. (A BroadcastChannel does something similar between tabs of the same site, which is handy for syncing a logout across tabs, but it can't reach other users.)

Server-Sent Events

Many "real-time" features only need data flowing one way: notifications, live scores, progress of a long job, prices, log tails, or text streamed from an AI model. For these, Server-Sent Events are simpler than WebSockets. They run over plain HTTP, and the browser reconnects automatically.

On the client you use EventSource:

JavaScript
// Read-only: listening to a real SSE endpoint
const source = new EventSource("/api/live-scores");

source.addEventListener("message", (event) => {    // events with no name
  console.log("update", JSON.parse(event.data));
});

source.addEventListener("goal", (event) => {       // events named "goal"
  const { team, minute } = JSON.parse(event.data);
  showBanner(`${team} scores in minute ${minute}!`);
});

source.addEventListener("error", () => {
  // Fired on every disconnect. readyState is CONNECTING (0) while the
  // browser retries by itself, CLOSED (2) once it has given up.
  console.log("connection state:", source.readyState);
});

// Stop listening (and stop automatic reconnects)
source.close();

The server answers with the content type text/event-stream and keeps the response open, writing events as plain text. Each event is a few field: value lines followed by a blank line:

TEXT
: lines starting with a colon are comments (handy as keep-alives)
retry: 5000

id: 41
data: {"home": 1, "away": 0}

id: 42
event: goal
data: {"team": "Home", "minute": 67}

data: first line
data: second line
  • data is the payload. Several data lines in one event are joined with newline characters.
  • event names the event type; without it, the event is a plain message.
  • id is remembered by the browser. After a reconnect, it sends the last ID in a Last-Event-ID request header, so the server can resume where the stream stopped.
  • retry tells the browser how many milliseconds to wait before reconnecting.

You can see how this format works by parsing a stream yourself. This demo builds an in-memory stream with new Response(text).body and reads it chunk by chunk, the same way a fetch()-based SSE client works:

JS Parsing a Server-Sent Events stream

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The third event has no id line, so it keeps the last ID it saw (42): that's the ID the browser would send after a reconnect. EventSource does all of this parsing for you. A hand-written reader like this one is useful when you need something EventSource can't do: it only makes GET requests and can't set custom headers such as Authorization. That's why tools that stream AI responses usually POST with fetch() and read the body stream themselves.

SSE and HTTP/1.1. Over HTTP/1.1, browsers allow only about six open connections per site, and each EventSource holds one for as long as it's open. With several tabs open, that limit is quickly reached. Over HTTP/2 or HTTP/3, which every modern server and CDN supports, many streams share one connection and the limit isn't a problem.

Choosing: polling, SSE or WebSocket?

Polling Server-Sent Events WebSocket
Direction Client asks Server โ†’ client Both ways
Latency Up to one interval Immediate Immediate
Protocol Plain HTTP Plain HTTP stream Upgraded connection
Data Anything Text (UTF-8) only Text and binary
Reconnects Not needed Automatic, resumes with Last-Event-ID You write it
Good for Rare updates, simple setups Feeds, notifications, progress, streamed text Chat, games, collaboration, live cursors

A practical way to decide:

  • If the client rarely needs fresh data, poll. It's the cheapest to build and run.
  • If only the server talks, use SSE. Client messages can still go through ordinary fetch() POST requests.
  • If both sides talk often, or you need binary data or very low latency, use a WebSocket.

A few production notes apply to both push technologies. Each open connection uses memory on the server, so they need servers built for many long-lived connections (Node.js handles this well; libraries such as ws and Socket.IO are common). Browsers can't add custom headers to a WebSocket, so authenticate with a cookie or by sending a token in the first message, and avoid tokens in the URL, where they end up in server logs. Check the Origin header on the server, because any web page can try to open a WebSocket to your server. Finally, WebTransport is a newer API built on HTTP/3 for low-latency and unreliable data (useful for games). It isn't supported in every browser yet, so WebSockets remain the dependable choice.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which feature does a WebSocket have that Server-Sent Events don't?

    SSE is one-way (server to client) and text-only. WebSockets are two-way and carry text or binary messages.
  2. 2. What happens if you call socket.send() while readyState is CONNECTING?

    Wait for the open event before sending. (After the socket closes, send() no longer throws; data is just discarded.)
  3. 3. Why should reconnect delays grow exponentially and include random jitter?

    Backoff spreads the load over time, and jitter keeps clients that disconnected together from returning together.
  4. 4. An SSE client reconnects after a network drop. How can the server know which events it missed?

    Events with an id line are remembered. On reconnect, EventSource sends Last-Event-ID so the server can resume the stream.
  5. 5. Why do many apps send their own "ping" messages over a WebSocket?

    Protocol-level ping frames aren't available to JavaScript, so an application heartbeat is how a client notices a dead connection.

Summary

  • Polling asks repeatedly; it's simple but wasteful and delayed. Long polling holds each request open until there's news.
  • WebSocket (wss://) is a permanent two-way connection: listen for open, message, error and close, check readyState, and send() text or binary data.
  • Design a small message protocol (JSON with a type, plus an id to match replies) and treat incoming data as untrusted.
  • WebSockets don't reconnect themselves: use exponential backoff with jitter, resume from the last message, and add a heartbeat to detect dead connections.
  • Server-Sent Events (EventSource) stream text one way over HTTP, with named events, automatic reconnects, retry and Last-Event-ID.
  • Choose polling for rare updates, SSE for server-to-client feeds, and WebSockets for frequent two-way traffic.

Next: JavaScript Security Basics โ€” protect your pages from XSS, clickjacking and other common attacks.