I'm building NextJS app with a streaming API route. If the client cancels the request (like closing the browser tab), I'd like to clean up resources and finish the response ASAP. Is there a way to detect request cancellation in nextjs route handler on Vercel?
I tried a few approaches: • Implementing a cancel function in the ReadableStream constructor • Listening for abort using req.signal.addEventListener • Setting the req.signal.onabort function
All three approaches work with next dev server but don't do anything when deployed on Vercel. In the Vercel logs, I can see it just streams the whole response and ignores all 3 functions/handlers. Sometimes it calls some of these handlers after function times out, but not consistently. Relevant conversation with no solution yet: https://community.vercel.com/t/req-signal-addeventlistener-doesnt-work-in-vercel-function/1123
Example of an app route handler with this behavior (where I tried implementing all approaches): https://github.com/langtail/vercel-nextjs-stream-cancel/blob/main/app/stream-test/route.ts
To reproduce, just open this route in browser and cancel the request. Or call it with curl and kill it after few seconds.
In the Vercel logs, I can see the function ran for 10 seconds (until timeout) even if I cancelled the request after a few seconds.