Unfortunately, adding an onabort-handler for my SSE-endpoints has only been possible with a workaround which you can see in this minimum reproducible example.
Creating an interval which prevents the request from getting garbage collected makes the onabort work properly. Stream.close() also doesn't call onabort (which makes sense but isn't really practical if you just want to handle connection loss, no matter if the client aborted it or the server), it would be nice if the Stream-API could get extended to allow developers to handle disconnects in an intuitive way.
import { Elysia } from "elysia";
import { Stream } from "@elysiajs/stream";
// [1] => Uncommenting this makes onabort work properly (page close/client-side connection loss calls onabort)
// [2] => stream.close() doesn't trigger onabort as well
// Running the code like this leads to "connection closed" never getting logged even if it should happen
new Elysia()
.get("/", ({ request }) => {
request.signal.onabort = () => {
console.log("connection closed");
// [1]
// clearInterval(_);
};
// [1]
// const _ = setInterval(() => request.signal.aborted, Math.pow(2, 31) - 1);
return new Stream(async (stream) => {
stream.send("test");
// [2]
// stream.close();
});
})
.listen(3000);
Unfortunately, adding an onabort-handler for my SSE-endpoints has only been possible with a workaround which you can see in this minimum reproducible example.
Creating an interval which prevents the request from getting garbage collected makes the onabort work properly. Stream.close() also doesn't call onabort (which makes sense but isn't really practical if you just want to handle connection loss, no matter if the client aborted it or the server), it would be nice if the Stream-API could get extended to allow developers to handle disconnects in an intuitive way.