Server-Sent Events: how to test an SSE stream with curl, JavaScript and Python
Server-Sent Events (SSE) are one long HTTP response that the server keeps writing to. They are how most AI chat APIs stream tokens, and how plenty of dashboards push live updates. They are also awkward to test: Swagger UI and many GUI clients show the stream only once it has finished, a proxy can quietly buffer it, and the reconnect behaviour only shows up when a connection actually drops.
This post tests a real stream from the command line, from JavaScript and from Python, then turns the checks into an automated suite. Every example runs against https://api.testingapis.com/api/stream/sse, a free SSE endpoint with no key and open CORS. All the output below was captured on 22 November 2026.
Watch a stream with curl
-N turns off curl's output buffering, so each event prints as it arrives. -i shows the headers:
$ curl -i -N "https://api.testingapis.com/api/stream/sse?count=3&interval=300"
HTTP/1.1 200 OK
content-type: text/event-stream
cache-control: no-cache
x-accel-buffering: no
transfer-encoding: chunked
: connected, streaming events 1..3
retry: 3000
id: 1
event: message
data: {"id":1,"message":"Event 1 of 3","timestamp":"2026-11-22T05:14:48.675Z"}
id: 2
event: message
data: {"id":2,"message":"Event 2 of 3","timestamp":"2026-11-22T05:14:48.975Z"}
id: 3
event: message
data: {"id":3,"message":"Event 3 of 3","timestamp":"2026-11-22T05:14:49.276Z"}
event: done
data: {"total":3}Three things to check before reading any events:
| Check | Why |
|---|---|
content-type: text/event-stream | Browsers' EventSource refuses anything else and fires error |
No content-length, chunked or HTTP/2 framing | A length means the server built the whole body first, so nothing streamed |
cache-control: no-cache | Stops a cache or CDN storing the stream and replaying it |
x-accel-buffering: no is a hint to nginx not to buffer. The format itself (id, event, data, retry and : comments) is covered in the Server-Sent Events lesson. This post is about testing it.
Test Last-Event-ID by hand
When a connection drops, a client reconnects and sends the last id it saw in a Last-Event-IDrequest header. A server that supports resuming carries on after that event. You don't need to drop a real connection to test it, just send the header:
$ curl -N -H "Last-Event-ID: 2" "https://api.testingapis.com/api/stream/sse?count=4&interval=200"
: connected, streaming events 3..4
retry: 3000
id: 3
event: message
data: {"id":3,"message":"Event 3 of 4","timestamp":"2026-11-22T05:14:49.542Z"}
id: 4
event: message
data: {"id":4,"message":"Event 4 of 4","timestamp":"2026-11-22T05:14:49.743Z"}
event: done
data: {"total":4}Asked to resume after 2, the server starts at 3. Now the same request against the stock ticker stream:
$ curl -N -H "Last-Event-ID: 2" "https://api.testingapis.com/api/stream/sse/stock?count=4&interval=200"
retry: 3000
id: 1
event: tick
data: {"tick":1,"symbol":"AAPL","name":"Apple Inc.","price":230.19,"change":2.67, ...}
id: 2
event: tick
data: {"tick":2,"symbol":"MSFT","name":"Microsoft Corp.","price":444.51,"change":6.40, ...}
...It ignores the header and starts again from 1. That is legal: the spec lets a server do what it likes with Last-Event-ID. But a client of that stream gets events 1 and 2 twice after every reconnect, so it has to deduplicate by id. Having one stream that resumes and one that doesn't is handy: your client should cope with both, and your tests should be able to tell them apart.
EventSource in the browser
Browsers have a built-in client. Default events arrive on message; named ones, like done here, need their own listener:
const es = new EventSource(
"https://api.testingapis.com/api/stream/sse?count=2&interval=200"
);
es.addEventListener("message", (e) => console.log("message", e.lastEventId, e.data));
es.addEventListener("done", (e) => {
console.log("done", e.data);
es.close(); // without this, EventSource reconnects 3 s later, forever
});$ node --experimental-eventsource es.mjs
message 1 {"id":1,"message":"Event 1 of 2","timestamp":"2026-11-22T05:15:48.464Z"}
message 2 {"id":2,"message":"Event 2 of 2","timestamp":"2026-11-22T05:15:48.665Z"}
done {"total":2}Node 24 has EventSource too, behind --experimental-eventsource; without the flag you get ReferenceError: EventSource is not defined. Two limits decide whether you can use it at all:
| Limit | What it means |
|---|---|
| No custom headers | You can't send Authorization. Only cookies (with withCredentials) or a token in the URL |
| GET only | No request body, so it can't call an AI API that wants a POST with a prompt |
It also reconnects on its own whenever the stream ends, which turns a finished stream into a request every few seconds unless you call close(). The lesson shows that loop with timestamps.
Read SSE with fetch, so you can send headers
When you need a bearer token or a POST, read the stream with fetch and parse it yourself. The parser is short. The parts people get wrong are a line split across two chunks, \r\n line endings, and several data: lines in one event, which must be joined with a newline:
// Reads a text/event-stream with fetch, so you can send any header.
export async function* readSse(url, { headers = {}, signal } = {}) {
const res = await fetch(url, {
headers: { Accept: "text/event-stream", ...headers },
signal,
});
const type = res.headers.get("content-type") ?? "";
if (!res.ok || !type.startsWith("text/event-stream")) {
throw new Error(`Expected an event stream, got ${res.status} ${type}`);
}
const decoder = new TextDecoder();
let buffer = "";
let event = { type: "message", data: [], id: undefined };
for await (const chunk of res.body) {
buffer += decoder.decode(chunk, { stream: true });
const lines = buffer.split(/\r\n|\r|\n/);
buffer = lines.pop(); // the last piece may be half a line
for (const line of lines) {
if (line === "") {
// A blank line ends the event. No data lines means nothing to send.
if (event.data.length) {
yield { type: event.type, id: event.id, data: event.data.join("\n") };
}
event = { type: "message", data: [], id: undefined };
continue;
}
if (line.startsWith(":")) continue; // comment or heartbeat
const colon = line.indexOf(":");
const field = colon === -1 ? line : line.slice(0, colon);
let value = colon === -1 ? "" : line.slice(colon + 1);
if (value.startsWith(" ")) value = value.slice(1);
if (field === "data") event.data.push(value);
else if (field === "event") event.type = value;
else if (field === "id") event.id = value;
// "retry" only matters to a client that reconnects by itself.
}
}
}import { readSse } from "./sse-client.js";
const t0 = Date.now();
const url = "https://api.testingapis.com/api/stream/sse?count=3&interval=500";
for await (const e of readSse(url, { headers: { Authorization: "Bearer test-token" } })) {
console.log(`+${((Date.now() - t0) / 1000).toFixed(1)}s`, e.type, e.id ?? "-", e.data);
if (e.type === "done") break;
}$ node watch.mjs
+0.2s message 1 {"id":1,"message":"Event 1 of 3","timestamp":"2026-11-22T05:15:31.298Z"}
+0.7s message 2 {"id":2,"message":"Event 2 of 3","timestamp":"2026-11-22T05:15:31.798Z"}
+1.2s message 3 {"id":3,"message":"Event 3 of 3","timestamp":"2026-11-22T05:15:32.298Z"}
+1.2s done - {"total":3}The timestamps are the useful part. The stream was asked for 500 ms between events and they arrive 500 ms apart, so nothing between here and the server is buffering. If all three showed the same time, something is holding the response back.
An automated SSE test suite
The same client makes a node:test suite with no mock server. It checks the three things that break most often: events are streamed rather than buffered, ids are in order and the stream ends cleanly, and reconnecting with Last-Event-ID leaves no gaps or repeats.
import { test } from "node:test";
import assert from "node:assert/strict";
import { readSse } from "./sse-client.js";
const BASE = "https://api.testingapis.com/api/stream";
async function collect(url, headers) {
const events = [];
const times = [];
const t0 = Date.now();
for await (const e of readSse(url, { headers, signal: AbortSignal.timeout(15_000) })) {
events.push(e);
times.push(Date.now() - t0);
if (e.type === "done") break;
}
return { events, times };
}
test("events arrive one at a time, not all at the end", async () => {
const { times } = await collect(`${BASE}/sse?count=4&interval=300`);
// 4 messages 300 ms apart: the first and last should be ~900 ms apart.
// A buffering proxy delivers them together, so the gap is near zero.
assert.ok(times[3] - times[0] > 600, `gap was ${times[3] - times[0]} ms`);
});
test("ids increase by one and the stream ends with done", async () => {
const { events } = await collect(`${BASE}/sse?count=5&interval=100`);
const messages = events.filter((e) => e.type === "message");
assert.deepEqual(messages.map((e) => Number(e.id)), [1, 2, 3, 4, 5]);
assert.deepEqual(JSON.parse(events.at(-1).data), { total: 5 });
});
for (const path of ["sse?count=5&interval=100", "sse/stock?count=5&interval=100"]) {
test(`${path.split("?")[0]} resumes after Last-Event-ID without gaps or repeats`, async () => {
const first = await collect(`${BASE}/${path}`);
const before = first.events.filter((e) => e.id).slice(0, 2); // pretend we dropped here
const resumed = await collect(`${BASE}/${path}`, { "Last-Event-ID": before.at(-1).id });
const ids = [...before, ...resumed.events.filter((e) => e.id)].map((e) => Number(e.id));
assert.deepEqual(ids, [1, 2, 3, 4, 5]);
});
}$ node --test sse.test.js
✔ events arrive one at a time, not all at the end (1063.9486ms)
✔ ids increase by one and the stream ends with done (511.6633ms)
✔ sse resumes after Last-Event-ID without gaps or repeats (676.8103ms)
✖ sse/stock resumes after Last-Event-ID without gaps or repeats (864.306ms)
ℹ tests 4
ℹ pass 3
ℹ fail 1
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
[
1,
2,
+ 1,
+ 2,
3,
4,
5
]The resume test passes for /api/stream/sse and fails for the stock stream, which replays 1 and 2. That failure is the point: it is exactly what your suite should report for a server that ignores the header. Point BASE at your own API and keep the tests.
Two things to keep in mind when you do. Run the timing test through the same proxy, load balancer and CDN your users hit, because a bare local server never buffers. And always pass a signal with a timeout, or a stream that never sends done hangs the test run.
Test SSE in Python with httpx
In Python, httpx streams the body with client.stream() and iter_lines(). This script reads two events, drops the connection, and resumes with Last-Event-ID:
import json
import httpx
URL = "https://api.testingapis.com/api/stream/sse"
def read_sse(client, url, headers=None):
"""Yield (event, id, data) tuples from a text/event-stream."""
with client.stream("GET", url, headers={"Accept": "text/event-stream", **(headers or {})}) as r:
r.raise_for_status()
assert r.headers["content-type"].startswith("text/event-stream")
event, event_id, data = "message", None, []
for line in r.iter_lines():
if line == "":
if data:
yield event, event_id, "\n".join(data)
event, event_id, data = "message", None, []
continue
if line.startswith(":"):
continue
field, _, value = line.partition(":")
value = value.removeprefix(" ")
if field == "data":
data.append(value)
elif field == "event":
event = value
elif field == "id":
event_id = value
# The read timeout is the longest gap allowed between two chunks, not a limit on the whole stream.
timeout = httpx.Timeout(10.0, read=5.0)
last_id = None
with httpx.Client(timeout=timeout) as client:
for event, event_id, data in read_sse(client, f"{URL}?count=5&interval=200"):
print(event, event_id, json.loads(data))
last_id = event_id or last_id
if event_id == "2":
break # simulate a dropped connection
print(f"--- reconnecting with Last-Event-ID: {last_id}")
for event, event_id, data in read_sse(client, f"{URL}?count=5&interval=200", {"Last-Event-ID": last_id}):
print(event, event_id, json.loads(data))
if event == "done":
break$ python sse_client.py
message 1 {'id': 1, 'message': 'Event 1 of 5', 'timestamp': '2026-11-22T05:15:54.114Z'}
message 2 {'id': 2, 'message': 'Event 2 of 5', 'timestamp': '2026-11-22T05:15:54.314Z'}
--- reconnecting with Last-Event-ID: 2
message 3 {'id': 3, 'message': 'Event 3 of 5', 'timestamp': '2026-11-22T05:15:54.402Z'}
message 4 {'id': 4, 'message': 'Event 4 of 5', 'timestamp': '2026-11-22T05:15:54.607Z'}
message 5 {'id': 5, 'message': 'Event 5 of 5', 'timestamp': '2026-11-22T05:15:54.808Z'}
done None {'total': 5}requests works the same way with stream=True and iter_lines(). Checked against this endpoint, both deliver events as they arrive.
Read timeouts on a quiet stream
A read timeout applies to each gap between chunks, not to the whole response. If a stream goes quiet for longer than the timeout, the client gives up. Here the events are 3 seconds apart and the read timeout is 2:
import httpx
with httpx.stream("GET", "https://api.testingapis.com/api/stream/sse?count=3&interval=3000",
timeout=httpx.Timeout(10.0, read=2.0)) as r:
for line in r.iter_lines():
print(repr(line))': connected, streaming events 1..3'
'retry: 3000'
''
'id: 1'
'event: message'
'data: {"id":1,"message":"Event 1 of 3","timestamp":"2026-11-22T05:15:55.685Z"}'
''
httpx.ReadTimeout: The read operation timed outThe first event arrives at once, then the wait for the second one fails. Either set the read timeout above the longest gap you expect, or have the server send a comment line such as : ping every few seconds. Comments reset the timer, and every client ignores them.
Calling the stream from a page on localhost
From a browser, a fetch with an Authorization or Last-Event-ID header is a cross-origin request with a preflight. The server has to allow both headers, or the stream never starts:
$ curl -s -X OPTIONS -D - -o /dev/null -H "Origin: http://localhost:5173" \
-H "Access-Control-Request-Method: GET" \
-H "Access-Control-Request-Headers: authorization,last-event-id" \
https://api.testingapis.com/api/stream/sse
HTTP/1.1 204 No Content
access-control-allow-headers: authorization,last-event-id
access-control-allow-methods: GET
access-control-allow-origin: *If your own API answers the preflight without those headers, EventSource may still work (it sends neither header on the first request) while your fetch client fails with a CORS error. Test both.
Common SSE problems and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| All events arrive at once at the end | A proxy or compression middleware buffers the response | Send X-Accel-Buffering: no, turn off gzip for text/event-stream, flush after each event |
EventSource fires error straight away | Wrong content type, a non-200 status, or a CORS failure | Check with curl -i; the type must be text/event-stream |
| The client reconnects every few seconds after the stream ends | EventSource reconnects on every close | Call close() on your end event, or answer the reconnect with 204 |
| Duplicate events after a reconnect | The server ignores Last-Event-ID | Resume on the server, or deduplicate by id on the client |
| The last event never shows up | No blank line after it before the stream closed | End every event with an empty line |
| JSON.parse fails on some events | Multi-line data joined without \n, or a line split across chunks | Buffer partial lines and join data lines with a newline |
| ReadTimeout on a quiet stream | The gap between events is longer than the read timeout | Raise the read timeout, or send : ping heartbeats |
| Only six streams work at once | The browser limit of six HTTP/1.1 connections per origin | Serve over HTTP/2, or share one stream between tabs |
Questions
Is there a free public SSE endpoint for testing?
Yes. /api/stream/sse sends numbered events and supports Last-Event-ID; count sets 1 to 100 events and interval 100 to 5000 ms between them. /api/stream/sse/stock sends a deterministic stock ticker as tick events. Neither needs a key.
What is Last-Event-ID?
A request header the client sends when it reconnects, holding the id of the last event it received. EventSource sends it automatically. With fetch you keep track of the id and send it yourself, as in the examples above.
Why does Swagger UI show nothing until the stream ends?
Swagger UI buffers the whole response before showing it, and so do many HTTP tools. A tool that buffers can't tell you anything about timing. curl -N always shows the real timing.
SSE or WebSockets?
SSE when only the server talks: notifications, progress, AI token streams. It is plain HTTP, so auth, proxies and logging work as usual. WebSockets when both sides send messages; the WebSocket echo server guide has one to test against. For describing an SSE stream in an API spec, see streaming APIs in OpenAPI 3.2.
The streaming API reference also has NDJSON, chunked, JSON array and slow drip endpoints, for testing other kinds of streamed responses.