#Response stream on close

11 messages · Page 1 of 1 (latest)

twin drift
#

I'm returning a stream here for SSE. I wanted to know if it's possible to get a callback when the client closes the connection? Because I need to close the stream and unsubscribe the client then

    return new Response(responseStream.readable, {
      status: 200,
      headers: {
        Connection: "keep-alive",
        "Cache-Control": "no-cache, no-transform",
        "Content-Type": "text/event-stream",
        "Access-Control-Allow-Origin": "*",

        //nginx disable buffering
        "X-Accel-Buffering": "no",
      },
    });```
swift agateBOT
#

Hi @twin drift. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the information provided in the extracts, it seems that there is an open issue on Astro's GitHub regarding the ReadableStream in the response body not being canceled when the client closes the connection. This issue seems to be similar to what you're experiencing.

In the issue, a user suggests a potential fix that involves using the getReader() method on the response body and then setting up an event listener on the close event of the response. When the close event is triggered, the cancel() method is called on the reader. Here's the suggested code:

const reader = await webResponse.body.getReader();
res.on("close", () => {
   reader.cancel();
})
let result = await reader.read();
while (!result.done) {
   res.write(result.value);
   result = await reader.read();
}

Please note that this is a suggestion from a user and may not be a definitive solution. You can follow the progress of this issue on Astro's GitHub (https://github.com/withastro/astro/issues/9068) for updates or potential fixes in the future.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@twin drift kapa.ai is still learning and improving, please let us know how it did by reacting below

twin drift
#

How can I do it with a TransformStream

#

@swift agate

swift agateBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Sorry @twin drift, I seem to be having a bit of trouble. Don't worry though, I've pinged my supprt and they will try to fix me up! :technologist:

Perhaps try again in 15mins?

twin drift
#

@swift agate How can I do it with a TransformStream

swift agateBOT
#

Let me check the knowledge base for you. One moment! :books:

#

I'm sorry, but the provided extracts do not contain information on how to handle client disconnection with a TransformStream in Astro. The extracts only mention the use of ReadableStream.

For more detailed information, you might want to refer to the official Astro documentation (https://docs.astro.build) or ask for help in the Astro community on GitHub or Discord.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: