How to Send Server-Sent Events with Bun.serve
With Bun.serve, if you pass an async generator function to new Response and set Content-Type to text/event-stream, you get a Server-Sent Events (SSE) endpoint. Each string you yield reaches the client as soon as it is yielded.
This works for one-way, continuous data flow from the server to the browser, such as notifications or progress display (real-time updates, push delivery). The browser receives the stream with EventSource. However, if you write it the simplest way, the connection is closed once the gap between events exceeds 10 seconds. In addition to the basic approach, I tested in a local environment how to keep the connection from being closed, how to clean up when the client disconnects, and how the browser reconnects.
The test environment was Ubuntu 24.04 (x86_64), Bun 1.4.4, TypeScript 5.9.3 (@types/bun 1.4.4), curl 8.5.0, and Chromium 157. All servers ran on localhost over HTTP/1.1. I did not test HTTPS, HTTP/2, setups with a proxy or load balancer in between, Firefox or Safari, or delivery across multiple servers. I checked the official documentation in the source files of the tested version (tag bun-v1.4.4) on GitHub, and the links point there.
Passing an async generator to Response
The shortest approach is the async generator method described on the Server-Sent Events page of the official guide. In Bun, you can pass an async generator function directly to new Response. The following server, when accessed at /events, sends three events one second apart and then ends.
// Basics of SSE. Connecting to /events sends 3 events, one per second, then ends.
const server = Bun.serve({
port: 3000,
routes: {
"/events": (req, server) => {
// Keeps the connection from being cut when no data is sent for more than 10 seconds.
server.timeout(req, 0);
return new Response(
async function* () {
try {
for (let n = 1; n <= 3; n++) {
yield `data: ${n}件目のイベントです\n\n`;
await Bun.sleep(1000);
}
} finally {
console.log("ストリームを閉じました");
}
},
{
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
},
},
);
},
},
});
console.log(`起動しました: ${server.url}`);
Each event consists of a data: body line followed by an empty line. As the MDN explanation of SSE describes, messages are separated by two newlines. That is why each yielded string ends with \n\n. The meaning of server.timeout(req, 0) is covered in a later section.
I started the server with bun server.ts and accessed it with curl using -N (print received data immediately, without buffering). The number at the start of each line is the time elapsed since curl started. I added the elapsed time by piping the curl output to another process. All curl output in this article was recorded the same way, and the command notation omits that part.
$ curl -sS -i -N http://localhost:3000/events
[ 0.0秒] HTTP/1.1 200 OK
[ 0.0秒] Content-Type: text/event-stream
[ 0.0秒] Cache-Control: no-cache
[ 0.0秒] Date: Sun, 22 Nov 2026 00:15:04 GMT
[ 0.0秒] Transfer-Encoding: chunked
[ 0.0秒]
[ 0.0秒] data: 1件目のイベントです
[ 0.0秒]
[ 1.0秒] data: 2件目のイベントです
[ 1.0秒]
[ 2.0秒] data: 3件目のイベントです
[ 2.0秒]
The headers were as I set them, except that Transfer-Encoding: chunked was added instead of Content-Length. The events arrived one second apart. They were sent at each yield rather than all at once after the whole stream was generated. When the generator function finished, the response ended too, and the server printed a message saying the stream was closed (the text of the finally log in the code above).
When type-checking with TypeScript, you need to be careful with lib in tsconfig.json. With a configuration where lib is ["ESNext"] and types includes bun, tsc passed. However, when I added "DOM" to lib, passing an async generator function to new Response produced the following error. The code in this article is type-checked with a configuration that does not include DOM in lib.
server.ts(10,9): error TS2345: Argument of type '() => AsyncGenerator<string, void, unknown>' is not assignable to parameter of type 'BodyInit | null | undefined'.
event, id, and retry, and the browser's EventSource
Besides data, SSE has event to name an event, id to number it, and retry to tell the client how long to wait before reconnecting. Lines starting with : are ignored as comments (MDN's description of each field and the stream format). I used all of them and checked how the browser receives them. The server is as follows.
// Sends event, id, retry, multi-line data, and a comment. If Last-Event-ID is present, resumes from there.
const server = Bun.serve({
port: 3001,
routes: {
"/": new Response(await Bun.file("./index.html").text(), {
headers: { "Content-Type": "text/html; charset=utf-8" },
}),
"/events": (req, server) => {
server.timeout(req, 0);
const lastId = Number(req.headers.get("last-event-id") ?? "0");
console.log(`接続されました(Last-Event-ID: ${req.headers.get("last-event-id")})`);
return new Response(
async function* () {
// Tells the browser to reconnect 1000 milliseconds after a disconnect.
yield "retry: 1000\n\n";
yield ": これはコメントです\n\n";
for (let id = lastId + 1; id <= lastId + 2; id++) {
await Bun.sleep(300);
yield `id: ${id}\ndata: ${id}件目\n\n`;
}
// Adding event makes it a named event. Splits data across two lines.
yield `event: notice\ndata: 1行目\ndata: 2行目\n\n`;
// When the function ends here, the response ends too (the browser reconnects).
},
{ headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } },
);
},
},
});
console.log(`起動しました: ${server.url}`);
The <script> in the browser-side index.html is as follows. It creates an EventSource, receives unnamed events with onmessage and event: notice events with addEventListener("notice", …), and adds one line per event to the page.
<script>
// Elapsed time since the page was opened.
const ms = () => `${Math.round(performance.now())}ms`;
const log = (text) => {
const li = document.createElement("li");
li.textContent = text;
document.getElementById("log").append(li);
};
const es = new EventSource("/events");
es.onopen = () => log(`open(接続しました、${ms()})`);
es.onmessage = (e) => log(`message: data=${JSON.stringify(e.data)} lastEventId=${e.lastEventId}`);
es.addEventListener("notice", (e) => log(`notice: data=${JSON.stringify(e.data)}`));
es.onerror = () => log(`error(readyState=${es.readyState}、${ms()})`);
window.stopSse = () => es.close();
</script>
I opened this page in Chromium and stopped it by calling es.close() once ten lines had appeared. The screen after that is shown below.

The screen shows the following.
- Each connection delivered two events without an
eventfield asmessage, ande.lastEventIdheld theidvalue. - The
event: noticeevent did not go toonmessage. It went to thenoticelistener. The twodatalines were joined with a newline (\n) into one string. - The
retryline and the comment line did not trigger any handler.
When the response ends, the browser reconnects with Last-Event-ID
The error on line 5 appeared when the server's generator finished and the response closed. At that moment, readyState was 0 (CONNECTING), and EventSource did not close but kept reconnecting. The error appeared at 613ms and the next open at 1615ms, so the gap was about one second, which matches the retry: 1000 I sent.
The reconnect request included a Last-Event-ID header. The request headers the browser sent and the server log for its two connections are shown below.
リクエスト: /events accept=text/event-stream last-event-id=(なし)
リクエスト: /events accept=text/event-stream last-event-id=2
接続されました(Last-Event-ID: null)
接続されました(Last-Event-ID: 2)
The client sent 2, the id of the last event it received, so the server resumed from the third event. This is why lines 7 and 8 on the screen show lastEventId=3 and 4. By reading this header, the server can tell where to resume. To resume, however, the server must keep the events it has already sent.
For EventSource, the server finishing the response counts as a disconnect, and it keeps reconnecting at the interval set by retry. When there is nothing more to send and you do not want it to reconnect, call close() on the client side, as described in MDN's explanation of how to close an event stream.
When there is no data for a while, the connection is closed
According to the official documentation on idleTimeout, Bun.serve closes a connection that has no sending or receiving activity for 10 seconds by default. This applies even while a response is being streamed. SSE connections tend to have gaps between events, so this applies to them.
So I prepared a stream that sends one event, stays silent for 15 seconds, and then sends another, and compared three approaches.
// Sends one event, stays silent for 15 seconds, then sends another. Compares which methods avoid being cut off midway.
const headers = { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" };
function quietStream(label: string, heartbeat: boolean) {
const t0 = Date.now();
const sec = () => ((Date.now() - t0) / 1000).toFixed(1);
return async function* () {
try {
yield `data: ${label} の1件目\n\n`;
for (let i = 0; i < 3; i++) {
await Bun.sleep(5000);
// If heartbeat is true, sends a comment line every 5 seconds.
if (heartbeat) yield ": ping\n\n";
}
yield `data: ${label} の2件目(15秒後)\n\n`;
} finally {
console.log(`${label}: 接続から ${sec()}秒で finally に来ました`);
}
};
}
Bun.serve({
port: 3002,
routes: {
// Does nothing (the default idleTimeout is 10 seconds).
"/plain": () => new Response(quietStream("plain", false), { headers }),
// Disables the idle timeout for this request only.
"/no-timeout": (req, server) => {
server.timeout(req, 0);
return new Response(quietStream("no-timeout", false), { headers });
},
// Keeps the timeout as is, but sends a comment every 5 seconds.
"/heartbeat": () => new Response(quietStream("heartbeat", true), { headers }),
},
});
console.log("起動しました");
The curl commands in this section also used an option to print the elapsed time (such as -w), but the commands and output omit that part. For /plain, which does nothing, curl stopped with exit code 18 before the second event arrived. All three runs were cut off 12.0 seconds after the connection started. This is not exactly the 10 seconds stated in the documentation, but a stream that sends nothing for 15 seconds was cut off in the middle.
$ curl -sS -N http://localhost:3002/plain
[ 0.0秒] data: plain の1件目
[ 0.0秒]
[ 12.0秒] curl: (18) transfer closed with outstanding read data remaining
The server console printed the following warning.
warn: Bun.serve() timed out a request after 10 seconds. Pass `idleTimeout` to configure.
/no-timeout, which calls server.timeout(req, 0), received the second event at 15 seconds and finished normally. As described in the server.timeout documentation, this changes the timeout only for that request, and passing 0 disables the timeout.
$ curl -sS -N http://localhost:3002/no-timeout
[ 0.0秒] data: no-timeout の1件目
[ 0.0秒]
[ 15.0秒] data: no-timeout の2件目(15秒後)
[ 15.0秒]
/heartbeat, which leaves the timeout unchanged and sends a : ping comment line every 5 seconds, also received everything to the end. Comments do not call EventSource handlers, so the connection can be kept alive without changing the receiving code. Sending comment lines periodically to keep a connection open is also described in MDN's format explanation.
$ curl -sS -N http://localhost:3002/heartbeat
[ 0.0秒] data: heartbeat の1件目
[ 0.0秒]
[ 5.0秒] : ping
[ 5.0秒]
[ 10.0秒] : ping
[ 10.0秒]
[ 15.0秒] : ping
[ 15.0秒]
[ 15.0秒] data: heartbeat の2件目(15秒後)
[ 15.0秒]
You can also raise the idleTimeout for the whole server. However, according to the documentation, the upper limit is 255 seconds, and it affects all other requests as well. If you only want it to apply to SSE endpoints, server.timeout(req, 0) limits the scope more precisely.
Note that the generator in /plain did not stop at the point (12 seconds) when the connection was cut. The server log reads "plain: reached finally 15.0 seconds after the connection started." It reached finally for the first time when it tried to yield the second event after 15 seconds.
Cleaning up when the client disconnects
When the client disconnects midway, such as when the user closes a browser tab, the server needs to stop timers, unsubscribe from message brokers, and so on. The official guide says that finally is called for an async generator, and cancel() is called for a ReadableStream (async generator, ReadableStream). I created two endpoints that each send an event every 0.5 seconds, stopped curl after 1.8 seconds, and checked the behavior.
const headers = { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" };
Bun.serve({
port: 3003,
routes: {
// For an async generator: finally is called.
"/generator": (req, server) => {
server.timeout(req, 0);
const t0 = Date.now();
return new Response(
async function* () {
let n = 0;
try {
while (true) {
yield `data: ${++n}\n\n`;
await Bun.sleep(500);
}
} finally {
console.log(`generator: 接続から ${Date.now() - t0}ms で finally(${n}件 yield したところ)`);
}
},
{ headers },
);
},
// For a ReadableStream: cancel is called.
"/stream": (req, server) => {
server.timeout(req, 0);
const t0 = Date.now();
let timer: Timer;
let n = 0;
const stream = new ReadableStream({
start(controller) {
timer = setInterval(() => controller.enqueue(`data: ${++n}\n\n`), 500);
},
cancel() {
clearInterval(timer);
console.log(`stream: 接続から ${Date.now() - t0}ms で cancel(${n}件 enqueue したところ)`);
},
});
return new Response(stream, { headers });
},
},
});
When I ran timeout 1.8 curl -sS -N http://localhost:3003/generator and similar commands, curl stopped after receiving four events from the generator and three from the stream. The server log was as follows.
generator: 接続から 2002ms で finally(5件 yield したところ)
stream: 接続から 1797ms で cancel(3件 enqueue したところ)
In both cases, the cleanup code was called. The difference was in timing. The cancel() of the ReadableStream was called right away, at about 1.8 seconds when curl disconnected. The finally of the async generator ran at 2.0 seconds, when Bun.sleep(500) finished and the fifth event was yielded. As with /plain in the previous section, the generator did not stop after the disconnect until its next yield.
When events arrive only rarely, an async generator keeps running after a disconnect until the next event. For sources that deliver events through callbacks, such as message brokers or timers, the official guide also recommends ReadableStream. If you want to unsubscribe at almost the same moment as the disconnect, write the stream with ReadableStream and stop it in cancel(). In my test, it was called at about 1.8 seconds, when curl disconnected.
To receive SSE from Bun, read it with fetch
Bun 1.4.4 does not have EventSource. typeof EventSource returned undefined. When you want to receive SSE from a Bun script or between servers, read the body as a stream with fetch and split it on blank lines. I ran the following client against the first server.ts.
// Receives SSE from Bun. Reads the body as a stream with fetch and splits on blank lines.
console.log(`typeof EventSource: ${typeof EventSource}`);
const res = await fetch("http://localhost:3000/events");
console.log(res.status, res.headers.get("content-type"));
let buffer = "";
for await (const chunk of res.body!.pipeThrough(new TextDecoderStream())) {
buffer += chunk;
let end: number;
while ((end = buffer.indexOf("\n\n")) !== -1) {
const message = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
const data = message
.split("\n")
.filter((line) => line.startsWith("data:"))
.map((line) => line.slice(5).trimStart())
.join("\n");
console.log(`受け取りました: ${data}`);
}
}
console.log("ストリームが終わりました");
$ bun client.ts
typeof EventSource: undefined
200 text/event-stream
受け取りました: 1件目のイベントです
受け取りました: 2件目のイベントです
受け取りました: 3件目のイベントです
ストリームが終わりました
This client only extracts the data lines. To branch processing by event, or to reconnect with Last-Event-ID after a disconnect, you need to implement the EventSource behavior covered in the earlier section yourself.





