Server-Sent Events (SSE) look like ordinary HTTP responses, but a stream that stays open for minutes changes how authentication, authorisation, rate limiting, proxies and logging behave. SSE is the transport behind most LLM token streaming APIs, behind MCP's Streamable HTTP transport, and behind countless dashboards and notification feeds. It is simple by design: the server answers a request with Content-Type: text/event-stream and keeps writing lines of text. That simplicity hides a set of security questions that do not arise with short request and response exchanges.
This guide explains the SSE protocol details that matter for security, then covers authentication and token lifetime on long-lived streams, cross-origin access, connection limits and resource exhaustion, proxy and gateway behaviour, reconnection and replay with Last-Event-ID, the specific risks of consuming and serving LLM streaming APIs, and MCP's requirements for SSE. Bidirectional sockets are covered separately in our WebSocket Security Guide.
Key takeaways
- An SSE stream authorises once, at connection time. If permissions or tokens change during the stream, the server must check again or close the stream.
- The browser
EventSourceAPI sends cookies whenwithCredentialsis set, so cookie-authenticated streams need CORS and CSRF thinking just like any other credentialed request. - Every open stream holds a connection, memory and often an upstream call. Cap streams per identity, per tenant and globally, and set maximum stream durations.
- Reverse proxies buffer and time out by default. Misconfiguring them for streaming leads teams to disable timeouts entirely, which turns the proxy into a resource exhaustion target.
- LLM streaming APIs can report an error after the HTTP status is already 200. Clients and gateways must inspect events, not just status codes, before trusting or billing a response.
- MCP servers using Streamable HTTP must validate the
Originheader, and locally they should bind only to localhost.
How SSE works, and what matters for security
The WHATWG HTML Standard defines SSE and the EventSource interface. The details below are taken from that specification.
- Format. The response has MIME type
text/event-streamand is always decoded as UTF-8. Each event is a set of lines with the fieldsevent(event type),data(payload, which can span several lines),id(sets the last event ID) andretry(reconnection time in milliseconds). Other fields are ignored, and lines starting with a colon are comments. - Dispatch. An event is dispatched only when a blank line arrives. An incomplete event at the end of the stream is discarded. Lines may end in CRLF, LF or CR.
- Reconnection. When a connection drops with a plain network error, the browser reconnects automatically after the reconnection time and sends a
Last-Event-IDheader if it has seen an ID. Redirects with 301 and 307 are followed. A server can tell the client to stop reconnecting with HTTP 204 No Content. - Failure. The connection fails permanently, without reconnecting, if the response status is not 200 or the content type is not
text/event-stream. - Requests.
EventSourcemakes a GET request with cache modeno-store. Its options object provideswithCredentialsfor cookies, and in practice browser SSE clients rely on cookies or the URL rather than anAuthorizationheader. Non-browser clients, including LLM SDKs and MCP clients, typically use POST or GET with custom headers and parse the stream themselves.
Three security consequences follow. First, line framing is the injection boundary: any server code that writes untrusted text into a data field without handling CR and LF can let that text start a new field or a new event. Second, automatic reconnection means a client will keep presenting its credentials to the server, and possibly to a redirect target, until told to stop. Third, status codes only arrive once, at the start: anything that goes wrong later has to be signalled inside the stream.
Authentication on long-lived streams
Choosing a credential
- Bearer tokens in headers are the right choice for server-to-server and SDK clients, including LLM APIs and MCP clients. They avoid ambient browser credentials and the CSRF class of problems.
- Cookies are the practical choice for browser
EventSourceclients. UseHttpOnly,Secureand an appropriateSameSitesetting, and treat the stream endpoint as a credentialed cross-origin target (see below). - Tokens in the URL are a common workaround for the header limitation. Avoid long-lived tokens in query strings, because URLs end up in proxy logs, browser history and analytics. If you must, issue a single-use, short-lived stream ticket bound to the user and the stream path, exchanged from an authenticated POST immediately before the stream opens. The HTML Standard itself suggests a unique identifier in the URL as a way to tie connections to clients, since IP addresses are unreliable for that purpose. A ticket is a better form of that idea than a reusable token.
Our JWT and Session Tokens in Code and Logs Guide covers how tokens leak through URLs and logs.
Token expiry mid-stream
A token validated when the stream opened may expire, be revoked, or lose a role while the stream is still sending data. HTTP does not re-authenticate an open response. Decide explicitly how your service behaves:
- Set a maximum stream duration no longer than the access token lifetime, then close the stream. The client reconnects and presents a fresh token.
- For streams that carry sensitive or per-user data, check revocation or session state on a timer and close streams whose session has ended.
- When a user's permissions change, close their open streams. Keep an index of open streams by identity so you can do this.
Per-event authorisation
Broadcast-style SSE (one stream, many topics) is where data leaks happen. Every event written to a stream must be checked against the identity that opened that stream, not against the topic subscription made when it opened. If a user is removed from a project, events for that project should stop on their existing connection, not just on the next one.
Cross-origin access, CORS and CSRF
The HTML Standard specifies that new EventSource(url, { withCredentials: true }) sets the request's credentials mode to "include". The request is then subject to CORS: the browser will only expose the stream to page script if the response carries an Access-Control-Allow-Origin header naming the calling origin and Access-Control-Allow-Credentials: true.
- Never reflect the request
OriginintoAccess-Control-Allow-Originon a credentialed stream endpoint. That lets any site read the user's live data feed. Our CORS Misconfiguration Guide covers safe allow-lists. - Even when CORS blocks reading, a cross-site GET with cookies still reaches your server. A stream endpoint that triggers work on open (starting a job, subscribing to a paid upstream feed) is a CSRF target. Keep stream opens side-effect free, or require a token that a cross-site page cannot obtain.
- Validate the
Originheader server-side on stream endpoints that use cookie authentication, and reject unknown origins before doing any work.
Connection limits and resource exhaustion
An SSE connection is cheap for a client to open and expensive for a server to hold. Each stream occupies a socket, buffers, often a thread or task, and for LLM or agent streams an upstream model call that costs money. Attackers do not need volume: a modest number of slow, never-closing streams can exhaust a service.
| Limit | Why it matters | Starting point (NHI Mgmt Group recommendation) |
|---|---|---|
| Concurrent streams per identity | Stops one user, API key or agent holding hundreds of streams | Low single digits for users; sized per workload for service identities |
| Concurrent streams per tenant and globally | Protects shared capacity and upstream quotas | Set below the capacity at which latency degrades |
| Stream open rate | Limits reconnect storms and abuse of automatic retry | Rate limit opens per identity and per source |
| Maximum stream duration | Forces re-authentication and bounds resource use | Shorter than the access token lifetime |
| Idle timeout | Closes streams that are no longer useful | Close after a period with no application events |
| Output size per stream | Bounds memory and cost, especially for generated output | Cap bytes or tokens per stream |
The HTML Standard notes that browsers limit connections per server, so opening many pages that each use SSE can exhaust that limit for the user. That is a usability issue for legitimate users, but it also hints at the server side: the per-connection model is the scaling unit. For connections that come from automated clients and agents, see our AI Agent Rate Limits guide.
Reconnection storms
Automatic reconnection is a feature that can turn into a self-inflicted denial of service. If a server restarts, every client reconnects after roughly the same delay. Use the retry field to set a sensible reconnection time, add server-side jitter when shedding load, and return HTTP 204 to clients that should stop entirely, for example after logout or when a feature is disabled. Return a non-200 status to clients whose credentials are no longer valid, since the specification says the connection then fails without reconnecting.
Proxies, gateways and load balancers
Streaming has to survive every hop between client and origin. The defaults of common proxies work against it, and the fixes are often too broad.
- Buffering. In nginx,
proxy_bufferingis on by default, which means responses are collected into buffers rather than passed to the client immediately. nginx documents that buffering can be switched off per response by sending anX-Accel-Buffering: noheader from the upstream. Prefer disabling buffering only on stream locations, or per response, rather than globally. - Read timeouts. nginx's
proxy_read_timeoutdefaults to 60 seconds and applies between two successive reads, not to the whole response. A stream that sends nothing for 60 seconds is closed. The right fix is a keepalive comment line, which the HTML Standard suggests sending about every 15 seconds to keep legacy proxies from dropping idle connections. Raising the timeout to hours instead lets dead or malicious connections pin resources indefinitely. - Caching. Stream endpoints must never be cached. Send
Cache-Control: no-storeand confirm that no CDN or proxy cache rule matches the stream path. - Chunking and compression. The HTML Standard notes that HTTP chunking added by a layer that is unaware of timing can hurt reliability. Compression layers that wait to fill a block can also delay events. Test the full path with real traffic.
- Header handling. Make sure gateways strip internal headers such as
X-Accel-Bufferingfrom client requests and do not let clients influence upstream buffering decisions.
Web application firewalls and API gateways often inspect complete bodies. For a stream, they see a body that never completes. Confirm whether your gateway inspects SSE at all, and if it does not, make sure the origin enforces its own input validation and output filtering. For LLM traffic specifically, our AI Gateway and LLM Gateway Guide covers gateway placement.
Event IDs, Last-Event-ID and replay
When a client reconnects, it sends the last event ID it received in the Last-Event-ID request header. Servers that support resumption use it as a cursor to replay missed events. That makes it a security-relevant input.
- Treat
Last-Event-IDas untrusted. Validate its format and length, and never use it directly in a query. - Scope IDs to the stream and identity. A client must not be able to supply another user's event ID and receive replayed events from that user's stream.
- Re-run authorisation on replayed events. Permissions may have changed while the client was disconnected.
- Bound the replay window by time and count so that a crafted old ID cannot trigger an expensive full history replay.
- Do not put secrets or internal identifiers in event IDs. They are stored by the client and sent back in headers that may be logged.
Consuming and serving LLM streaming APIs
Most LLM APIs stream generated tokens over SSE. Anthropic's streaming documentation is a useful worked example of the patterns involved: setting "stream": true on a Messages request returns a sequence of named events (message_start, content block start, delta and stop events, message_delta and message_stop), with ping events that may appear at any point. Several security and reliability points generalise across providers.
Errors arrive after the 200
Anthropic documents that the API can send an error event inside the stream, for example an overloaded_error during high load, and that because the HTTP status is already 200 by then, clients must handle errors in the stream itself. Any gateway, proxy or logging layer that records success from the status code alone will misreport these failures. Monitoring for streamed APIs must parse events.
Unknown events and partial output
- Anthropic advises that new event types may be added over time and that code should ignore unrecognised event types. Build parsers that tolerate new events but do not act on them.
- Tool use input arrives as partial JSON fragments that must be accumulated and parsed only once the content block is complete. Never execute a tool call, render markup or act on structured output from a partial stream. Validate the complete object first.
- If your application streams model output straight to a browser, any output filtering, HTML encoding or data loss prevention has to work incrementally, because text is shown to the user before the full response is known. Filters that only run on the final response are too late.
Usage and cost
Anthropic documents that the usage counts in message_delta are cumulative, so the latest value should be used rather than summing. Getting this wrong inflates or undercounts metered usage. Because streamed generation can run long, enforce output caps and per-key concurrency limits at your gateway. Abandoned client connections may not stop upstream generation unless you cancel the upstream request, so propagate client disconnects to the model call. Our Denial-of-Wallet and AI Agent Cost Runaway Guide covers the cost side.
Keys behind streaming proxies
Many teams put a thin streaming proxy in front of an LLM provider so that browsers never see the provider API key. That is correct, but the proxy then becomes the credential holder and an open relay unless it authenticates its own callers, applies per-user limits and restricts which models and parameters can be requested. See our LLMjacking Guide for how exposed keys and open proxies are abused.
SSE in MCP servers
The Model Context Protocol specification (version 2025-06-18) defines a Streamable HTTP transport in which a single MCP endpoint accepts POST and GET, and the server may answer with text/event-stream to stream messages. It replaces the older HTTP+SSE transport from protocol version 2024-11-05. The specification's security warning states that servers MUST validate the Origin header on all incoming connections to prevent DNS rebinding attacks, SHOULD bind only to localhost when running locally, and SHOULD implement proper authentication for all connections.
- Session IDs. A server may assign an
Mcp-Session-Idat initialisation. The specification says it SHOULD be globally unique and cryptographically secure. Treat it as a session identifier, not as authentication: still verify the caller's credential on every request. - Resumability. Event IDs, if used, MUST be globally unique across all streams within a session, and servers MUST NOT replay messages that would have been delivered on a different stream. This is the per-stream cursor rule described above, made normative.
- Termination. After a server terminates a session it MUST respond to that session ID with 404, and clients SHOULD send DELETE when they no longer need a session. Clean up stream state on both paths.
- Versioning. Clients MUST send
MCP-Protocol-Versionon subsequent requests, and servers MUST reject invalid or unsupported versions with 400.
For moving off the deprecated transport, see our MCP SSE to Streamable HTTP Migration guide.
Logging and detection
- Log stream opens and closes with identity, client, origin, duration, bytes and close reason. Many access logs only write a line when a response completes, so long streams may be invisible until they end.
- Alert on identities holding unusual numbers of concurrent streams, rapid reconnect loops and streams far longer than the expected duration.
- Count in-stream error events separately from HTTP errors so that partial failures appear in dashboards.
- Do not log full event payloads by default. Streams of model output or user data are high-volume and often sensitive.
Common failure patterns
- Authorise once, stream forever. A revoked user keeps receiving data on a stream opened hours earlier.
- Reflected CORS on a credentialed stream. Any website can read the logged-in user's live feed.
- Long-lived tokens in stream URLs. Tokens end up in proxy and CDN logs.
- Newline injection. Untrusted text written into
datalines without escaping lets attackers forge events. - Timeouts raised to hours. A fix for dropped streams becomes an easy way to exhaust the proxy.
- Success measured by status code. In-stream LLM errors are recorded as successful calls.
- Acting on partial output. Tool calls or rendered markup are processed before the stream completes and is validated.
- No upstream cancellation. Clients disconnect, but the model keeps generating and billing.
- MCP servers without Origin checks on localhost, open to DNS rebinding.
Practitioner checklist
- Use header bearer tokens for non-browser clients and short-lived single-use tickets, not reusable tokens, where browser URLs must carry credentials.
- Cap stream duration below token lifetime and close streams when sessions end or permissions change.
- Authorise every event, including replayed events, against the identity that owns the stream.
- Use an explicit CORS allow-list and validate
Originon cookie-authenticated and MCP stream endpoints. - Set per-identity, per-tenant and global concurrent stream limits, open rate limits and output caps.
- Disable proxy buffering only on stream paths, keep read timeouts modest and send keepalive comments.
- Send
Cache-Control: no-storeand confirm no CDN cache rule matches stream paths. - Escape CR and LF in any untrusted data written to the stream.
- Parse in-stream error events in clients, gateways and monitoring, and propagate client disconnects to upstream calls.
- Validate and scope
Last-Event-ID, and bound the replay window.
Standards and references
- WHATWG HTML Standard: Server-sent events
- Model Context Protocol specification 2025-06-18: Transports
- Anthropic: Streaming Messages
- nginx: ngx_http_proxy_module
- OWASP: API Security Top 10 2023
- OWASP: Application Security Verification Standard 5.0
- OWASP: Top 10 for LLM Applications 2025
- NIST: SP 800-53 Rev. 5 (SC-5 Denial-of-service Protection, SC-8 Transmission Confidentiality and Integrity)
Related NHI Mgmt Group resources: WebSocket Security Guide · MCP SSE to Streamable HTTP Migration · CORS Misconfiguration Guide · AI Gateway and LLM Gateway Guide