Server-Sent Events in JavaScript: Stream Live Progress Without Polling

A report takes 20 seconds to generate. A file import needs a minute. An AI application produces its answer in small pieces. In all three cases, the browser needs updates while the server is still working. Asking the server for progress every second is possible, but it means sending a new HTTP request even when nothing has changed.

Server-sent events (SSE) offer a different approach: keep an HTTP response open and deliver updates as they become available. The browser exposes the EventSource API, which handles the event format and attempts to reconnect after interruptions. You can build a useful progress interface without introducing a WebSocket server or an external messaging library.

When should you choose SSE?

Start with the direction of communication, not the popularity of a protocol.

ApproachGood fitTrade-off
PollingInfrequent updates, simple infrastructureRepeated requests and delayed discovery
SSENotifications, progress, live feedsLong-lived connections and server-to-client delivery
WebSocketInteractive multiplayer or frequent two-way messagingMore connection and protocol management
Streaming fetchStreaming a POST response or custom headersYou implement framing and reconnection

An SSE connection is one-way. A user can still submit a form or cancel a job using an ordinary HTTP request. That request is independent of the stream. A useful architecture for an export service is a POST that creates a job, followed by a GET that subscribes to updates for that job.

Understand the wire format first

The server responds with Content-Type: text/event-stream. Its body consists of UTF-8 text with blank lines separating events. An event might look like this:

id: 42
event: progress
data: {"percent":40,"state":"running"}

event names the event type. If it is absent, the browser dispatches a standard message event. Each data line contributes to the event payload; consecutive data lines are joined with newline characters. id is an optional cursor, and retry can suggest a reconnect delay in milliseconds. Lines beginning with a colon are comments, useful for keeping idle connections active.

JSON is a convenient payload convention, not a requirement of SSE. For a JSON event, inspect only the value after data: with our JSON formatter and validator. The entire event stream is not a JSON document, so pasting it into a JSON parser will fail.

Build a small working server

This example uses Node.js and its built-in HTTP module. No packages are required. Save the following code as server.mjs. The server will serve a page at / and a simulated progress stream at /events.

import http from 'node:http';
import { readFile } from 'node:fs/promises';

const page = await readFile(new URL('./progress.html', import.meta.url));
const port = Number(process.env.PORT || 3000);

http.createServer((req, res) => {
  if (req.method !== 'GET') {
    res.writeHead(405, { Allow: 'GET' }).end();
    return;
  }
  if (req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    res.end(page);
    return;
  }
  if (req.url !== '/events') {
    res.writeHead(404).end('Not found');
    return;
  }

  res.writeHead(200, {
    'Content-Type': 'text/event-stream; charset=utf-8',
    'Cache-Control': 'no-store',
    'X-Accel-Buffering': 'no'
  });
  res.flushHeaders();
  res.write('retry: 3000\n\n');

  let progress = 0;
  let timer;
  function send() {
    progress += 10;
    const name = progress === 100 ? 'complete' : 'progress';
    const data = JSON.stringify({ percent: progress });
    const ready = res.write(`event: ${name}\ndata: ${data}\n\n`);
    // This tiny demo stops rather than queueing data for a slow client.
    if (!ready) {
      res.destroy();
      return;
    }
    if (progress === 100) res.end();
  }
  res.on('close', () => clearInterval(timer));
  timer = setInterval(send, 500);
}).listen(port, '127.0.0.1', () => {
  console.log(`Open http://127.0.0.1:${port}/`);
});

The response headers are sent immediately with flushHeaders(). A timer then emits a new progress update every half-second. When the last update arrives, the server sends a named complete event and ends the response. The close handler clears the timer whether the browser closes normally or the connection disappears.

X-Accel-Buffering: no is a hint understood by nginx in appropriate configurations. It is not a universal proxy directive. The example avoids compression and uses no-store so that an intermediary should not cache the stream. The small demonstration deliberately disconnects a slow client rather than accumulating data in memory.

This is a local simulation, not a job queue. Every connection starts a new simulated counter. Real work must be separate from the HTTP connection so that a network interruption does not restart a payment, export or file import.

Connect the browser with EventSource

Save this page as progress.html beside the server file:

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Live job progress</title>
<h1>Live job progress</h1>
<button id="start">Start demo</button>
<button id="stop" disabled>Disconnect</button>
<p><label for="bar">Job progress</label></p>
<progress id="bar" max="100" value="0"></progress>
<span id="number" aria-hidden="true">0%</span>
<p id="status" role="status">Idle</p>
<script>
const start = document.querySelector('#start');
const stop = document.querySelector('#stop');
const bar = document.querySelector('#bar');
const number = document.querySelector('#number');
const status = document.querySelector('#status');
let source;

function finish(message) {
  source?.close();
  source = undefined;
  status.textContent = message;
  start.disabled = false;
  stop.disabled = true;
  start.focus();
}

start.addEventListener('click', () => {
  bar.value = 0;
  number.textContent = '0%';
  start.disabled = true;
  stop.disabled = false;
  stop.focus();
  status.textContent = 'Connecting';
  source = new EventSource('/events');
  source.onopen = () => {
    status.textContent = 'Connected (demo restarts on reconnect)';
  };
  function update(event) {
    try {
      const { percent } = JSON.parse(event.data);
      if (!Number.isInteger(percent) || percent < 0 || percent > 100) {
        throw new Error('Invalid progress');
      }
      bar.value = percent;
      number.textContent = `${percent}%`;
      if (event.type === 'complete') {
        if (percent !== 100) throw new Error('Invalid completion');
        finish('Job complete');
      }
    } catch {
      finish('Invalid server response');
    }
  }
  source.addEventListener('progress', update);
  source.addEventListener('complete', update);
  source.onerror = () => {
    if (source.readyState === EventSource.CLOSED) {
      finish('Connection closed');
    } else {
      status.textContent = 'Disconnected; waiting to reconnect';
    }
  };
});
stop.addEventListener('click', () => finish('Disconnected'));
</script>
</html>

Start the server:

node server.mjs

Open http://127.0.0.1:3000/ and select Start demo. The native progress element advances from zero to 100. The status region announces connection changes and completion rather than reading every progress tick aloud. The Disconnect button closes the subscription; in a real service, cancelling the actual job requires a separate authorized action.

The browser validates the parsed percentage and inserts status text with textContent. Do not use innerHTML for arbitrary server-supplied strings. Our HTML escaping versus sanitizing guide explains why the rendering context matters even when data has already been parsed as JSON.

A critical detail is the call to close() when the application receives its completion event. A normal HTTP end-of-stream is otherwise a reason for EventSource to reconnect. Closing the object prevents an already completed demo from restarting automatically.

Test streaming with cURL

Open another terminal and run:

curl --no-buffer --include \
  --header 'Accept: text/event-stream' \
  http://127.0.0.1:3000/events

--no-buffer makes cURL write received output without its usual output buffering. You should see the response headers, then a sequence of events over about five seconds. If all events arrive together, investigate the layers between the process and the client.

Use the cURL command line builder to assemble the URL and Accept header, then append --no-buffer --include in your terminal. The builder prepares the command, but does not execute it. Test both the origin and your deployed URL, with credentials omitted from shared diagnostic logs.

Open the Network panel in browser DevTools as well. The response should stay pending while data arrives. Some browsers offer an EventStream inspection tab; if yours does not, inspect application logs and the raw stream using cURL.

Design reconnects for actual jobs

Imagine the client receives an event with ID 42 and loses its connection. On an automatic reconnect, EventSource can send Last-Event-ID: 42. This helps a server that stores an event history resume at the next event. It does not create that history for you.

For a simple progress display, you may not need a log of every increment. Store the current job state and return an authoritative snapshot when the client reconnects. For a notification feed where each message matters, use durable event IDs and a bounded replay history. If a cursor is too old, send a fresh snapshot or an explicit reset message rather than pretending nothing was missed.

sequenceDiagram
    participant B as Browser
    participant A as API
    participant W as Job worker
    B->>A: POST /jobs
    A-->>B: 202 and job ID
    A->>W: Enqueue work
    B->>A: GET /jobs/123/events
    A-->>B: Current snapshot
    W->>A: Persist progress
    A-->>B: Progress event
    Note over B,A: Connection interrupted
    B->>A: Reconnect with Last-Event-ID
    A-->>B: Replay or fresh snapshot
    W->>A: Persist completion
    A-->>B: Completion event

Adapt the sequence in the Mermaid live editor, or follow our API documentation tutorial to include authentication failures and expired jobs. The paths in this diagram illustrate a production design, not additional endpoints implemented in the demo.

Handle proxy buffering and connection limits

SSE is ordinary HTTP, but an ordinary response often finishes quickly. Some hosting platforms enforce execution timeouts or buffer responses until a threshold has been reached. A CDN may also have a maximum duration for a request. Check these limits rather than assuming the application code controls the entire connection.

For streams that can remain idle, send a comment such as : heartbeat\n\n periodically, choosing an interval below the relevant idle timeout. Heartbeats should not reset business progress or be displayed as notifications. They also cannot overcome a hard request-duration limit.

HTTP/1.1 browsers can impose a low per-origin connection limit across tabs. HTTP/2 can multiplex requests, subject to negotiated stream limits. Either way, avoid opening a connection for every small widget. A shared stream with named event types is often easier to manage. Monitor open connections, reconnect rates, queued bytes and resource use. If a client cannot keep up, pause, coalesce nonessential updates or disconnect it and allow recovery from a snapshot.

Keep the event endpoint private

The native EventSource constructor does not accept arbitrary request headers. For same-origin applications, a secure session cookie can authenticate the GET. Cross-origin connections need appropriate CORS policy, and credentialed requests require an explicitly allowed origin. See our CORS troubleshooting guide for the difference between browser policy and successful command-line requests.

Authorize the requested job against the logged-in user on every connection. Avoid putting reusable bearer tokens into URLs, since URLs can appear in logs and analytics. If custom authorization headers or a streaming POST body are required, consider fetch() with a stream reader instead, understanding that you must implement parsing and recovery.

An SSE GET should not create new irreversible work. Use a separately protected POST to start that work, rate-limit subscriptions, and close streams when authorization expires according to your application’s policy. Never use an event ID as an authorization credential.

A checklist before shipping

  • Verify events are delivered individually through the actual reverse proxy and CDN.
  • Test disconnection, reconnect, duplicate events and a cursor older than your retained history.
  • Check that a finished job is not restarted by a reconnect or page reload.
  • Test with two accounts to ensure neither can subscribe to the other’s jobs.
  • Test keyboard access, status announcements and slow connections.
  • Measure concurrent subscriptions and ensure timers, listeners and queued data are released.

For the protocol details, see MDN’s server-sent events reference and the HTML living standard.

SSE is a useful middle ground between periodic requests and a fully bidirectional protocol. If your next application needs live updates, start with one small endpoint and inspect its response with the cURL command builder before adding a more complex transport.

Premium is coming soon

An optional premium subscription to remove ads is planned. Subscriptions are not available yet.

You can keep using our free tools without an account.