Created
June 1, 2025 07:10
-
-
Save sommeeeer/24fcddcf1829ccb689f60b67f259162c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export default { | |
| fetch(req) { | |
| const url = new URL(req.url); | |
| if (url.pathname === "/sse-test") { | |
| let intervalId: ReturnType<typeof setInterval>; | |
| req.signal.addEventListener("abort", () => { | |
| console.log("Request aborted!"); | |
| }); | |
| const stream = new ReadableStream({ | |
| start(controller) { | |
| console.log("SSE: Client connected"); | |
| intervalId = setInterval(() => { | |
| const message = `data: ${new Date().toISOString()}\n\n`; | |
| try { | |
| console.log("SSE: Enqueuing data", message); | |
| controller.enqueue(new TextEncoder().encode(message)); | |
| } catch (e) { | |
| // This catch is a fallback, for debugging just in case, primary disconnect detection is via 'cancel' | |
| // in any case it is never called in the example reproduction repo | |
| console.error("SSE: Error enqueuing data:", e); | |
| clearInterval(intervalId); | |
| // Attempt to close if not already closed by 'cancel' | |
| try { | |
| console.log("SSE: attempting manual close"); | |
| controller.close(); | |
| } catch { | |
| console.error("SSE: Error closing stream:", e); | |
| } | |
| } | |
| }, 1000); | |
| }, | |
| }); | |
| return new Response(stream, { | |
| headers: { | |
| "Content-Type": "text/event-stream", | |
| "Cache-Control": "no-cache", | |
| Connection: "keep-alive", | |
| }, | |
| }); | |
| } | |
| return new Response("Not found", { status: 404 }); | |
| }, | |
| } satisfies ExportedHandler<Env>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment