← Writing

Server-Sent Events with EventSource

October 8, 20267 min read

javascriptsseeventsourcerealtime

Sometimes the UI only needs updates in one direction: server to browser. Job progress. Live logs. A notification feed. Stock ticks. You do not need a full duplex socket for that.

Server-Sent Events (SSE) keep one HTTP connection open and push plain-text events as they happen. In the browser you subscribe with the EventSource API.

Try it here

Click Connect. This page opens EventSource("/api/sse"). The server keeps the response open, sends a tick every second, and fires a named ping every five ticks. The stream ends after about fifteen ticks (or 20 seconds max). It also closes if you leave the tab, so a forgotten demo cannot hang forever.

Connection: idle

Live stream from /api/sse (ends in ~15 server ticks or 20s client max; closes when you leave)

  • Click Connect. The server keeps one HTTP response open and pushes ticks. It will shut itself down.

Open DevTools → Network, filter EventStream (or look for /api/sse), and watch the live data: payloads arrive on one connection.

The problem before SSE

HTTP is request and response. The browser asks, the server answers, then the conversation ends. Live UIs break that assumption: the interesting work happens on the server, and the client only needs to watch.

Before SSE, teams faked "the server talking first" with AJAX patterns that were never built for continuous notification. The two main ones, covered on web.dev, were polling and long polling.

Polling

The client asks again and again: "Anything new?" If not, the server returns empty. Wait. Ask again.

It is easy to ship (any REST endpoint works), but you pay for it:

  • Every poll is a full HTTP round trip, even when nothing changed
  • Poll too often and you burn bandwidth. Poll too rarely and the UI feels late
  • The server cannot speak when an event happens. Freshness is stuck to your timer

Polling answers "is there news?" on a schedule. It does not answer "here is news" at the moment the server knows.

Long polling (hanging GET / COMET)

Long polling is smarter about empty replies. If there is no data, the server holds the request open until something arrives (or a timeout fires). Then it responds, closes, and the client opens a new hanging request.

That cuts wasted empty responses, but you still do not get a real push channel:

  • Each delivery still ends the HTTP response
  • Busy streams mean constant reconnect churn
  • Older setups used brittle hacks, like script tags in an "infinite" iframe (web.dev)

So long polling is a better approximation of push, not push itself. The server delays the answer. The protocol still thinks in closed responses.

ApproachWho initiates?When the connection endsPain point
PollingClient on a timerAfter every answerOverhead and stale UI
Long pollingClient after each deliveryAfter each non-empty answerReconnect churn
SSEServer when events existWhen the subscription endsBuilt for this

What SSE changes

Once the connection is open, the server can push over that same HTTP response. Direction is one way: server → client. You listen with EventSource instead of writing another poll loop.

Unlike long polling, the response stays open across many messages. Unlike WebSockets, you stay on ordinary HTTP (text/event-stream) and get browser-native reconnect, event IDs, and named events for free (web.dev).

Client: EventSource

const source = new EventSource("/api/sse");

source.addEventListener("open", () => {
  console.log("open");
});

// Default events (no event: field) land as "message"
source.addEventListener("message", (e) => {
  const data = JSON.parse(e.data); // e.data is always a string
  console.log(data);
});

// Named events from the server: event: ping
source.addEventListener("ping", (e) => {
  console.log("ping", JSON.parse(e.data));
});

source.addEventListener("error", () => {
  // Network blip: the browser usually retries
});

// Stop listening (also stops auto-reconnect)
source.close();

readyState is CONNECTING (0), OPEN (1), or CLOSED (2). Same-origin rules apply. Cross-origin streams need CORS. EventSource only does GET.

Full reference: MDN EventSource.

Wire format

Respond with Content-Type: text/event-stream. Each event is text fields ending in \n, then a blank line \n\n:

data: hello\n\n

JSON on one line (what this demo uses):

data: {"tick":1,"message":"Hello from the server (#1)"}\n\n

Named event:

event: ping
data: {"tick":5,"note":"every 5 ticks"}

Useful fields from the SSE format:

FieldRole
data:Payload → event.data
event:Custom name → addEventListener(name)
id:Last-Event-ID for resume after reconnect
retry:Milliseconds before the browser retries
: commentIgnored by the client; useful as a keep-alive

Server shape (Next.js)

The demo route writes into a ReadableStream:

export async function GET() {
  const encoder = new TextEncoder();
  const stream = new ReadableStream({
    start(controller) {
      const send = (chunk: string) =>
        controller.enqueue(encoder.encode(chunk));

      send(": connected\n\n");

      let tick = 0;
      const timer = setInterval(() => {
        tick += 1;
        send(`data: ${JSON.stringify({ tick, message: `Hi (#${tick})` })}\n\n`);
        if (tick >= 15) {
          clearInterval(timer);
          controller.close();
        }
      }, 1000);
    },
  });

  return new Response(stream, {
    headers: {
      "Content-Type": "text/event-stream; charset=utf-8",
      "Cache-Control": "no-cache, no-transform",
      Connection: "keep-alive",
    },
  });
}

Plain Node is the same idea: set the SSE headers, res.write("data: …\n\n"), clear the interval when the request closes.

SSE vs WebSockets

Use WebSockets when you need near real-time traffic both ways (games state, collaborative cursors, chat on one channel).

Use SSE when updates are mostly server → client:

  • Friend status / news feeds
  • Progress bars and job streams
  • Dashboards that only display live data

You still send client → server with ordinary fetch when you need to. SSE gives you automatic reconnect, event IDs, and named events without a custom socket protocol.

Cancel and reconnect

  • Client: source.close() and the browser will not reconnect
  • Server: end the response (this demo does after 15 ticks), or return a non-SSE content type / non-200 to discourage reconnect
  • Default: if the connection drops, the browser retries after about three seconds unless you set retry:

When you intentionally finish a stream (progress hit 100%), close the EventSource in a done handler so you do not spin a new run. That is what the demo above does.

Gotchas

  1. Forgot \n\n and the browser never fires the event
  2. Named events vs onmessage: event: ping does not hit onmessage. Use addEventListener("ping")
  3. e.data is always a string. JSON.parse when you send JSON
  4. Some proxies buffer SSE. Cache-Control: no-cache and disabling response buffering help
  5. Without HTTP/2, browsers historically capped concurrent SSE connections per domain
  6. Serverless hosts time out long streams. Cap the demo (this one ends in about 15 to 20 seconds)

When to use it

Use SSE when the product story is "the server has news, the UI should update." Skip it when you need a continuous two-way channel on the same connection (that is WebSocket territory), or when you are shipping binary frames.

The live box at the top is the whole lesson in one gesture: one GET, many pushes, browser API included.

Further reading