Skip to content
Tutorials Center
My learning

Topics

Lesson 94 of 122 ยท Web APIs

Server-Sent Events

Stream live updates from a server with Server-Sent Events. Learn EventSource, the text/event-stream format, named events, IDs and automatic reconnection.

Many pages need to show things the moment they happen: a new comment, a delivery that changed status, a score in a live match or an AI answer arriving word by word. The browser could ask the server "anything new?" every few seconds, but that wastes requests and always lags behind.

Server-Sent Events (SSE) turn this around. The page opens one long-lived HTTP connection, and the server keeps it open and pushes messages down it whenever it has something to say. On the browser side the whole feature is a single object, EventSource, which also reconnects automatically if the connection drops. The traffic flows in one direction only, from server to browser, and that simplicity is SSE's biggest strength.

There is no server behind the editors on this page, so they can't receive a real stream. The live examples show what can run here: what happens when a connection fails, a parser for the stream format, and a simulated stream with the same API. The read-only snippets show the real thing, ready to use with your own server.

Connecting with EventSource

Create an EventSource with the URL of a stream on your server and listen for messages:

JavaScript
const source = new EventSource('/updates');

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

source.addEventListener('message', (event) => {
  console.log('New message:', event.data);
});

source.addEventListener('error', () => {
  console.log('Connection problem; readyState is', source.readyState);
});

You can also use the onopen, onmessage and onerror properties instead of addEventListener(). Each message event carries:

  • event.data: the message text (always a string; send JSON and parse it if you need structure).
  • event.lastEventId: the ID of the latest event, if the server sent one.
  • event.origin: the origin of the stream.

The readyState property tells you where the connection is:

Value Constant Meaning
0 EventSource.CONNECTING Connecting, or reconnecting after a drop
1 EventSource.OPEN Connected and receiving
2 EventSource.CLOSED Closed for good; the browser will not retry

To stop listening, call source.close(). The connection closes and readyState becomes 2.

Cross-origin streams

By default EventSource follows the same rules as fetch(): a stream on another origin works only if that server allows it with CORS headers. To send cookies along with a cross-origin request, pass an option:

JavaScript
const source = new EventSource('https://api.example.com/feed', { withCredentials: true });

When the connection fails

Run the example below. It tries to connect to a stream that doesn't exist, and logs each error event together with the readyState. In this sandbox the connection can never succeed.

Watching a connection fail

Depending on the browser and the kind of failure, you will see one of two patterns:

  • readyState is CONNECTING after the error. The browser treats the problem as temporary (a network failure) and will retry automatically after a short delay. That is why the example calls close() itself after three attempts.
  • readyState is CLOSED after the error. The server answered, but not with a valid stream (for example a 404 page or the wrong content type). The browser gives up for good.

Your own code should do the same: let short outages heal on their own, and show a message once the connection is closed for good.

The text/event-stream format

The server side of SSE is just an HTTP response that never quite finishes. It must be sent with the content type text/event-stream (encoded as UTF-8), and its body is plain text made of events separated by blank lines. Each line inside an event is a field:

TEXT
: this line is a comment and is ignored

data: The kettle has boiled

event: order-status
data: {"order": 1042, "status": "shipped"}
id: 57

data: A message can span
data: several data lines

retry: 10000
Field Effect
data: The message text. Several data lines in one event are joined with line breaks.
event: A name for the event type. Without it, the type is message.
id: An ID the browser remembers as the "last event ID".
retry: How many milliseconds the browser should wait before reconnecting.
: at the start A comment. Servers often send one every 15 to 30 seconds to keep proxies from closing an idle connection.

A single space after the colon is optional and removed. An event is only delivered when its blank line arrives, so a server should end every event with an empty line and then flush its output.

The parser below follows the same rules as the browser. Edit the stream text near the top of the script and watch how it is split into events.

How a stream is parsed

Notice that the last event (event: empty) produces nothing: it has no data, so the browser doesn't fire it. Also note that the event ID stays the same for later events until a new id: line changes it.

Named events

Events with an event: field are not delivered to onmessage. You listen for them by name with addEventListener():

JavaScript
const source = new EventSource('/orders/1042/stream');

source.addEventListener('order-status', (event) => {
  const update = JSON.parse(event.data);
  statusElement.textContent = update.status;
});

source.addEventListener('message', (event) => {
  // Only unnamed events end up here.
});

Named events let one stream carry several kinds of updates, each with its own handler. The next example uses a small FakeEventSource class that behaves like the real one: it extends EventTarget, has readyState, onmessage and close(), and sends a mix of named and unnamed events from a timer. In a real page, replace new FakeEventSource(...) with new EventSource('/scores') and the rest stays the same.

A live score feed (simulated)

Reconnection and missed events

Automatic reconnection is the feature that makes SSE so pleasant. If the connection drops (a train enters a tunnel, the server restarts), the browser waits a few seconds and connects again, all on its own. A retry: field from the server changes that waiting time.

Reconnecting alone would lose any events sent while the page was offline. That is what id: is for. When the browser reconnects, it sends the last ID it saw in a request header:

TEXT
GET /updates HTTP/1.1
Accept: text/event-stream
Last-Event-ID: 57

A well-written server reads Last-Event-ID and first sends everything that happened after event 57, then continues live. The browser does all of this for you; you only need to include IDs on the server side.

To stop the browser from reconnecting, either call close() in the page or have the server answer with HTTP status 204 No Content.

When to use SSE

SSE is a great fit when the server talks and the browser listens: notifications, live feeds, dashboards, progress bars for long jobs and streamed text responses. It is plain HTTP, so it works through most proxies and firewalls, and it needs no special server software.

Keep these limits in mind:

  • One direction only. To send something to the server, use an ordinary fetch() request. If both sides need to talk constantly, use WebSockets.
  • Text only. Binary data must be encoded (as Base64, for example).
  • Connection limits on HTTP/1.1. Browsers allow only about six connections per site over HTTP/1.1, and every open stream uses one, so many open tabs can starve the page. Over HTTP/2 and HTTP/3 many streams share one connection, so this mostly goes away.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In which direction do Server-Sent Events carry messages?

    SSE is a one-way push from server to browser. To send data to the server, use fetch(); for two-way messaging, use WebSockets.
  2. 2. Which content type must the server send for an SSE stream?

    EventSource only accepts responses served as text/event-stream. Anything else closes the connection.
  3. 3. The server sends event: price followed by data: 42 and a blank line. Which code receives it?

    Named events are dispatched under their own name. Only events without an event: field reach the message handler.
  4. 4. What ends one event in the stream and delivers it?

    Events are separated by an empty line. The browser fires the event when it reads that blank line.
  5. 5. Why should a server include id: lines?

    The browser remembers the last ID and sends it in the Last-Event-ID header when it reconnects, so no events are lost.

Summary

  • new EventSource(url) opens a long-lived connection that the server pushes messages down.
  • Listen for open, message and error; readyState is 0 (connecting), 1 (open) or 2 (closed); close() ends it.
  • The stream is text/event-stream text: data:, event:, id: and retry: lines, with a blank line ending each event.
  • Named events (event: name) need addEventListener('name', ...); they don't reach onmessage.
  • The browser reconnects automatically and sends Last-Event-ID so the server can fill the gap.
  • SSE is one-way and text-only; use fetch() to send data, or WebSockets for constant two-way traffic.

Next lesson: WebSockets, where the browser and server can both send messages at any time.