What Are Server-Sent Events (SSE)? Receive a Server Event Stream in the Browser
Server-sent events (SSE) is a one-way streaming method in which a browser keeps an HTTP connection open to receive text events from a server. The browser's EventSource reconnects when the connection is interrupted and can send the last event ID on a reconnect request when the server provides one. This alone does not guarantee durable storage, lossless replay, or exactly-once processing. Reliable delivery also requires correct stream framing, buffering and authentication settings, and an application replay policy.
Server-sent events (SSE) is a one-way streaming method in which a browser keeps an HTTP connection open to receive text events from a server. The browser's EventSource reconnects when the connection is interrupted and can send the last event ID on a reconnect request when the server provides one. This alone does not guarantee durable storage, lossless replay, or exactly-once processing. Reliable delivery also requires correct stream framing, buffering and authentication settings, and an application replay policy.
When is SSE a good fit?
SSE fits one-way updates from a server to a browser, such as notifications, job progress, and dashboard refreshes. The client sends commands through separate ordinary HTTP requests. If both sides need to initiate messages on the same connection, WebSocket may fit better. This is a choice based on transport requirements, not a performance guarantee.
The browser API is EventSource. It reconnects by default and exposes open, message, and error events. Use addEventListener() to receive named events. The standard EventSource constructor accepts a URL and an optional withCredentials option. It does not expose an interface for arbitrary request headers, methods, or bodies. If a bearer header is required, reconsider the authentication design or consider a Fetch-based client designed for streaming.
Connect and receive events in the browser
const source = new EventSource("/events");
source.onopen = () => console.log("Stream connected");
source.onmessage = (event) => {
const update = JSON.parse(event.data);
renderUpdate(update);
};
source.addEventListener("progress", (event) => {
showProgress(JSON.parse(event.data));
});
source.onerror = () => {
// A temporary connection error is possible; check readyState and server health.
console.warn("Stream connection error", source.readyState);
};
// Stop automatic reconnection when leaving the view or ending the subscription.
function stopUpdates() {
source.close();
}This is an illustrative client example, not a result from a live server integration test. Check the server's data format and trust boundary before parsing JSON. An error event does not expose detailed HTTP response information; inspect browser developer tools' network records and server logs. readyState is CONNECTING, OPEN, or CLOSED. A browser may reconnect after a temporary disconnect; close() stops it.
The event format sent by the server
The response must use Content-Type: text/event-stream, and the stream is UTF-8 encoded. Each event is a text block terminated by a blank line. Each line consists of a field and value.
retry: 3000
: keep-alive comment
id: 1042
event: progress
data: {"job":"import-7","percent":60}
`data` carries the event data. Multiple `data:` lines are joined with newline characters.
`event` names a custom event; without it, the event type is `message`.
`id` sets the last event ID.
`retry` sets the reconnection delay as an integer number of milliseconds. A non-numeric value is ignored.
A line beginning with `:` is a comment and dispatches no event. It can be sent periodically to avoid intermediary idle timeouts, but choose an interval for your infrastructure.
Field names and values follow the specification's parsing rules. Always terminate an event block with a blank line; closing the connection does not dispatch a final incomplete block. The server must check not only its response headers but also whether application, web-server, and proxy output buffers actually flush the stream. MDN shows X-Accel-Buffering: no as a reverse-proxy example, but that setting is specific to some server configurations; configure the environment in use.
Reconnection and event resumption are different
When the browser reconnects, it can send a Last-Event-ID request header if an event ID was provided. The server can use that value to query an event log or cursor and send subsequent events. This requires the server to retain events, validate the cursor, and define behavior for old cursors or expired history. Emitting an id does not itself store or replay events. The standard also specifies that a server can use an HTTP 204 No Content response to tell the client to stop reconnecting.
Depending on when the network breaks and when the server records an event, events can be missed or duplicated. Give replayable events stable IDs, make client handling idempotent, and provide a recovery path such as full state resynchronization for expired cursors. SSE reconnection is a transport retry mechanism, not a database transaction or an exactly-once delivery contract.
Cross-origin access, authentication, connection limits, and operations
For a stream on another origin, the server must configure its CORS response correctly. To include cookies or other credentials, create new EventSource(url, { withCredentials: true }) and configure the server to allow credentialed access. A credentialed response cannot use Access-Control-Allow-Origin: *. Review CSRF and session policies when using cookie authentication. Avoid placing long-lived secret tokens in URL query strings, where they can appear in history and logs.
With HTTP/1.x, per-browser and per-domain connection limits can become a problem across multiple tabs. MDN warns that some browsers impose low limits. With HTTP/2, the client and server negotiate the number of concurrent streams. Check the actual limit for the browser and deployment. Avoid opening many connections per page; consider sharing one across tabs or using HTTP/2.
The server should clean up work when clients disconnect and account for periodic heartbeats, idle timeouts, proxy buffering, concurrent connection counts, and reconnect surges. Long-lived connections consume server resources, so apply authentication, access control, and connection limits, then check timeout and reconnect behavior in the actual deployment environment.
Troubleshooting
If the browser cannot open the connection, check the URL, HTTP status, `Content-Type: text/event-stream`, TLS, CORS, and authentication result.
If events arrive late in a burst, investigate buffering, compression, flush behavior, and idle limits in the app server and proxies.
If an event does not reach the page, check field-name casing, the blank-line terminator, `data:` formatting, and custom `event` listeners.
If events are missing or duplicated after reconnecting, inspect `id`, `Last-Event-ID`, server log retention, cursor expiry, and client idempotency.
If disconnections occur only on mobile or through a proxy, compare the heartbeat interval with infrastructure idle timeouts. Do not assume one universal interval.
Call `source.close()` when ending the connection, and have the server detect disconnects and clean up subscriptions and work.
Sources
[WHATWG HTML Standard: Server-sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html)
[MDN: Using server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events.)
[MDN: Server-sent events API](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events)
[MDN: EventSource interface](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)
[MDN: EventSource constructor](https://developer.mozilla.org/en-US/docs/Web/API/EventSource/EventSource)
[WHATWG Fetch Standard: CORS protocol and credentials](https://fetch.spec.whatwg.org/#cors-protocol-and-credentials)