Requests and responses
Streaming and SSE
Send a response bit by bit with @senrijs/senri/streaming. Server-Sent Events
import { } from "@senrijs/senri";
import { } from "@senrijs/senri/streaming";
const = ();
.("/events", (, ) =>
(, async () => {
.(() => .("disconnected"));
for (let = 0; !.; ++) {
await .({ : "tick", : (), : () });
await .(1000);
}
}),
);| Function | Sends |
|---|---|
stream(c, run) | Bytes |
streamText(c, run) | Text |
streamSSE(c, run) | Server-Sent Events |
- When the client disconnects,
s.abortedbecomestrueand the functions registered withs.onAbort()run s.write()waits until the reader catches up
When an error happens midway
Once the response has started, it cannot become a 500. Pass onError to write something last and close normally. Without it, the error is logged and the connection is cut (so that a partial download does not look complete).
import { } from "@senrijs/senri/streaming";
.("/log", (, ) =>
(
,
async () => {
for (let ; ( = await ()) !== null; ) await .(`${}\n`);
},
{ : async (, ) => .("\n(failed midway)\n") },
),
);SSE heartbeat
streamSSE() first sends a : connected comment, so the headers arrive at once. After that, it sends a : ping comment every 5 seconds, because Bun (about 10 seconds) and proxies (often about a minute) close quiet connections.
- Change the interval with
{ heartbeat: 15_000 }, or stop it with{ heartbeat: false } - Clients ignore comments
compress()does not compress SSE
On Cloudflare Workers
A disconnect is noticed only at the next write. On a quiet stream, onAbort is not called (with the heartbeat, it was called within 15 seconds). Do not leave urgent cleanup to onAbort.