Request abortion while streaming response on vercel

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: req.signal.addEventListener doesn't work in Vercel function

Example of an app route handler with this behavior (where I tried implementing all approaches): vercel-nextjs-stream-cancel/app/stream-test/route.ts at main · langtail/vercel-nextjs-stream-cancel · GitHub

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.

1 Like

I tried running the app with next start and all 3 approaches work there, so it seems like it’s some issue with how vercel handles the API requests - probably a limitation of the vercel serverless runtime?

1 Like