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.
1export async function GET(req: NextRequest) {2 let aborted = false34 req.signal.onabort = () => {5 console.log('Request aborted')6 aborted = true7 cleanup()8 }910 try {11 // Your main logic here12 const result = await someAsyncOperation(req.signal)1314 if (aborted) {15 throw new Error('Request aborted')16 }1718 return NextResponse.json({ result })19 } catch (error) {20 if (error.name === 'AbortError' || aborted) {21 return NextResponse.json({ message: 'Request was aborted' }, { status: 499 })22 }23 // Handle other errors24 return NextResponse.json({ error: error.message }, { status: 500 })25 }26}2728function cleanup() {29 // Your cleanup logic here30 console.log('Performing cleanup operations')31}3233async function someAsyncOperation(signal: AbortSignal) {34 // Simulate a long-running operation that can be aborted35 return new Promise((resolve, reject) => {36 const timeout = setTimeout(() => resolve('Operation completed'), 5000)37 signal.addEventListener('abort', () => {38 clearTimeout(timeout)39 reject(new Error('Operation aborted'))40 })41 })42}
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.