I need to call cleanup code if the function is aborted. What I had working locally with next dev was using an event listener, but this is not called when deplyed on Vercel.
Is there a proper way to detect when a request has been cancelled?
Vercel Alum
Hi, ! Welcome to the Vercel Community
The approach you are using with addEventListener on req.signal is actually on the right track, but there's a slight modification we can make to ensure it works both locally and when deployed on Vercel.
Instead of using addEventListener, we can use the AbortSignal.onabort property, which is supported in both Node.js and Edge runtimes on Vercel.
exportasyncfunctionGET(req: NextRequest){
let aborted =false
req.signal.onabort=()=>{
console.log('Request aborted')
aborted =true
cleanup()
}
try{
// Your main logic here
const result =awaitsomeAsyncOperation(req.signal)
if(aborted){
thrownewError('Request aborted')
}
return NextResponse.json({ result })
}catch(error){
if(error.name ==='AbortError'|| aborted){
return NextResponse.json({ message:'Request was aborted'},{ status:499})
We use req.signal.onabort to set up the abort handler. This will be called if the request is cancelled.
We maintain an aborted flag to track the cancellation state throughout the request lifecycle.
In the someAsyncOperation function, we demonstrate how to make a cancellable operation using the AbortSignal. This is crucial for long-running operations that need to be cancellable.
In the error handling, we check for both AbortError and our aborted flag. This covers cases where the abort might be triggered by the operation itself or by our manual flag.
We use status code 499 for aborted requests, which is a common convention for client-closed requests.
Let us know how you get on!
Hi, that solution does not work for me. I copied your code into a new route, deployed using vercel --prod, sent a request using curl and immediately cancelled. I see the request logs show it ran for 5s and returned a 200 without logging anything, so it appears the function completed successfully and was not aborted.
Does it work when you deploy it? Is there any settings I need to change?
This topic is closed. It no longer accepts new replies.