{"canonical_url":"https://engineer.company/glossary/server-sent-events/","content_markdown":"# Server-sent events\n\n## What it is\n\nServer-sent events are a way for a web server to push messages to a page over\none ordinary HTTP response that it keeps open and writes into whenever there is\nnews. They are defined in the HTML Standard, maintained by the WHATWG, which\ndescribes both the text format of the stream and `EventSource`, the browser\ninterface that reads it. The name is often shortened to SSE, and the format is\noften called after its media type, `text/event-stream`.\n\nA page opens a stream with one line, `new EventSource(url)`. The browser sends a\n`GET` request, which may carry `Accept: text/event-stream`, and expects a\nresponse with status 200 and that content type. The server sends the headers and\nthen does not finish the body. Each time something happens, it writes a few\nlines of text, and the browser turns each block of lines into an event the page\ncan listen for.\n\nThe format is deliberately plain. A stream is always UTF-8, and every line is\none field. A `data` line carries the payload, and several `data` lines in a row\nare joined with line breaks. An `event` line gives the event a type, and without\none the type is `message`. An `id` line sets the ID of the last event, and a\n`retry` line sets how many milliseconds the browser waits before it reconnects.\nA line that starts with a colon is a comment, which the browser ignores. A blank\nline ends the block and dispatches the event, so a block cut off before its\nblank line is thrown away.\n\nReconnection is part of the standard. When the connection drops, the browser\nwaits for the reconnection time, which starts at a value of its own choosing,\naccording to the standard probably a few seconds, and then sends the request\nagain. If the server has given IDs to its events, the new request carries the\nlast one in a `Last-Event-ID` header, and the server can carry on from there.\nSome answers end the stream for good instead: a status other than 200 or a\ndifferent content type makes the browser give up and stop trying, and the\nstandard names 204 No Content as the way for a server to say that the stream is\nover.\n\nThe direction is one way only. After the opening request, nothing travels from\nthe page to the server on that connection; when the page has something to say,\nit sends a separate HTTP request.\n\n## Why it matters\n\nPlenty of features that look live only need one direction: the progress of a\nlong job, a notification, a figure on a dashboard, an answer that arrives in\nparts. Without a stream, the page has to poll. It asks every few seconds, most\nanswers say nothing has changed, and news waits up to one interval before anyone\nsees it. With a stream, the server writes the moment something happens.\n\nThe usual alternative for pushing data is WebSocket, which switches the\nconnection away from HTTP to a protocol of its own. Server-sent events stay\ninside HTTP from start to finish, so they pass through the same proxies and load\nbalancers as any other request, they use the same cookies and the same rules for\ncross-origin requests, and they can share one HTTP/2 connection with the rest of\nthe page. Reconnection and resuming from the last event come with the browser\ninstead of being code that every team writes for itself. WebSocket is still the\nright choice when the client has as much to say as the server, as in chat or a\nshared editor.\n\nThe format is not tied to the browser either. Any HTTP client can read it, and\nspecifications outside the web use it. In the Model Context Protocol, through\nwhich AI agents call tools, the Streamable HTTP transport lets a server answer a\nrequest either with one JSON object or with a `text/event-stream` response. On\nthat stream it may send notifications and requests of its own before the final\nresponse, and it can attach event IDs so that a client which loses the\nconnection resumes with `Last-Event-ID`. Streamable HTTP replaced HTTP+SSE, the\ntransport of the earlier protocol version 2024-11-05.\n\nThe limits are worth knowing before choosing it. The stream carries text only,\nso binary data has to be encoded as text first. The browser's `EventSource`\nconstructor takes a URL and one option, `withCredentials`, and nothing else, so\na page cannot add an `Authorization` header to the request.\n\n## What it looks like in practice\n\nThe exchange below follows a long export job. The browser has lost its\nconnection after event 41 and is reconnecting, so its request carries that ID,\nand the server carries on from event 42:\n\n```http\nGET /jobs/4471/events HTTP/1.1\nHost: example.com\nAccept: text/event-stream\nLast-Event-ID: 41\n\nHTTP/1.1 200 OK\nContent-Type: text/event-stream\nCache-Control: no-store\n\nretry: 5000\n\n: still working\n\nid: 42\nevent: progress\ndata: {\"done\": 120, \"total\": 400}\n\nid: 43\nevent: progress\ndata: {\"done\": 400, \"total\": 400}\n\nid: 44\nevent: finished\ndata: {\"report\": \"/jobs/4471/report.pdf\"}\n\n```\n\nThe `retry` line asks the browser to wait five seconds before any later\nreconnection, and the comment line carries no event at all; it is there to keep\nthe connection busy while the job is quiet. The page listens for the two event\ntypes by name:\n\n```js\nconst source = new EventSource(\"/jobs/4471/events\");\nsource.addEventListener(\"progress\", (event) =\u003e {\n  const { done, total } = JSON.parse(event.data);\n  showProgress(done / total);\n});\nsource.addEventListener(\"finished\", (event) =\u003e {\n  showReport(JSON.parse(event.data).report);\n  source.close();\n});\nsource.addEventListener(\"error\", () =\u003e {\n  if (source.readyState === EventSource.CLOSED) showRetryButton();\n});\n```\n\nThe call to `close()` matters. When the server ends a response normally, the\nbrowser treats it as a dropped connection and reconnects, so a stream for a\nfinished job would otherwise open again after five seconds. The `error` handler\ntells the two kinds of failure apart: while `readyState` is `CONNECTING`, the\nbrowser is still trying, and once it is `CLOSED`, it has given up.\n\nWork that goes on after the agent has its answer comes up on this site's page on\n[turning existing software into tools for AI agents](/ai-tools/). It describes\noffering a company's operations as tools, with an MCP server offering the same\noperations to the agents that speak it, and slow work moved onto a queue so that\nthe agent gets an answer while the work goes on. In the MCP specification, a\nserver can use an event stream like the one above to send its own requests or\nnotifications before the final response to the client's request.\n\n## Where it goes wrong\n\n**Events that arrive in bursts, or all at the end.** Something between the\nserver and the browser holds the response back. nginx, for one, buffers\nresponses from the server behind it by default, and passes a response on as it\narrives only when buffering is off. The HTML Standard also warns that HTTP\nchunking done by a layer that knows nothing about the stream's timing can make\nit unreliable. Turn buffering off for the stream's location, in nginx with\n`proxy_buffering off` or a response header of `X-Accel-Buffering: no`, flush the\noutput after every event in the server code, and test through the whole path,\nproxy included, rather than against the server alone.\n\n**Quiet streams cut off by a timeout.** A proxy that sees no bytes for a while\nassumes the connection is dead. In nginx, `proxy_read_timeout` defaults to 60\nseconds between two reads, after which the connection is closed, and the HTML\nStandard warns that some older proxies drop connections after a short timeout.\nIt suggests a comment line every 15 seconds or so, which costs a few bytes and\nwhich the browser ignores.\n\n**Events lost in a reconnection.** The browser sends `Last-Event-ID` only if the\nserver gave its events IDs, and the header helps only if the server can still\nfind what came after that ID. Give every event an ID that works as a cursor in\nthe stream, keep a window of recent events to replay, and send the full current\nstate when an ID is too old to resume from. The MCP specification adds a rule\nworth copying: IDs belong to one stream, and a server must not replay on one\nstream messages meant for another.\n\n**Reconnection that never stops, or stops for good.** A stream that ends\nnormally comes back after the reconnection time, again and again, so a finished\njob keeps reopening its stream unless the page calls `close()` or the server\nanswers the reconnection with 204. The opposite happens during a deploy. A proxy\nthat answers 502 or 503 while the servers restart gives every open `EventSource`\na status other than 200, and every one of them stops for good. Listen for\n`error`, and when `readyState` is `CLOSED`, create a new `EventSource` after a\nrandom delay that grows with each failure.\n\n**Too many streams for one browser.** Browsers limit how many connections they\nkeep open to one server, and a stream served over HTTP/1.1 holds one of them for\nas long as it lasts. The HTML Standard warns that a site where every open page\nhas its own `EventSource` can run into that limit. Serve the stream over HTTP/2,\nwhere streams share one connection and RFC 9113 recommends allowing at least 100\nat once, or share one `EventSource` between the tabs through a shared worker.\n\n**The token in the address.** Because `EventSource` cannot send an\n`Authorization` header, the quick fix is a token in the URL, where reverse\nproxies and access logs write it down. Authenticate the stream with the session\ncookie the page already has, adding `withCredentials` when the stream comes from\nanother origin, or with a short-lived, single-use ticket that the page fetches\nover an authenticated request just before it opens the stream.\n\n## Further reading\n\n- [HTML Standard: Server-sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html)\n  — the stream format, the `EventSource` interface, reconnection and the\n  authoring notes on proxies and connection limits.\n- [Transports - Model Context Protocol](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports)\n  — Streamable HTTP, where a server may answer with an event stream, and how a\n  broken stream resumes.\n- [RFC 9113: HTTP/2](https://www.rfc-editor.org/rfc/rfc9113) — streams that\n  share one connection, and the setting that limits how many are open at once.\n- [nginx: Module ngx_http_proxy_module](https://nginx.org/en/docs/http/ngx_http_proxy_module.html)\n  — `proxy_buffering`, the `X-Accel-Buffering` header and `proxy_read_timeout`.\n\n\u003chttps://engineer.company/glossary/server-sent-events/\u003e\n","date_modified":"2026-11-09T21:50:25Z","description":"How a server keeps one HTTP response open and writes events into it, what the browser does when it breaks, and the proxies that hold the events back.","formats":{"gemtext":"https://engineer.company/glossary/server-sent-events/index.gmi","gopher":"https://engineer.company/glossary/server-sent-events/gophermap","html":"https://engineer.company/glossary/server-sent-events/","json":"https://engineer.company/glossary/server-sent-events/index.json","markdown":"https://engineer.company/glossary/server-sent-events/index.md","pdf":"https://engineer.company/glossary/server-sent-events/index.pdf"},"kind":"page","language":"en","title":"What are server-sent events?","url":"https://engineer.company/glossary/server-sent-events/","version":1}