next.js: Api route req on close event not triggered when request is cancelled
Verify canary release
- I verified that the issue exists in the latest Next.js canary release
Provide environment information
Operating System:
Platform: linux
Arch: x64
Version: #22 SMP Tue Jan 10 18:39:00 UTC 2023
Binaries:
Node: 18.14.2
npm: 9.5.0
Yarn: 1.22.19
pnpm: N/A
Relevant Packages:
next: 13.4.10-canary.8
eslint-config-next: 13.4.8
react: 18.2.0
react-dom: 18.2.0
typescript: 5.0.4
Next.js Config:
output: N/A
Which area(s) of Next.js are affected? (leave empty if unsure)
Middleware / Edge (API routes, runtime)
Link to the code that reproduces this issue or a replay of the bug
https://codesandbox.io/p/sandbox/blissful-driscoll-y78mrd
To Reproduce
- open the link from above
- click on “Trigger API call” button
- click on “Cancel API call” button and note in browser network tab that the request which was previously pending is now cancelled
- note how
req.on("close"
event handler didn’t run and API route work is still being done
Describe the Bug
Request close event is not firing in the API route when the caller cancels the request
Expected Behavior
Request close event should be fired so that any necessary cleanup can be done
Which browser are you using? (if relevant)
No response
How are you deploying your application? (if relevant)
No response
About this issue
- Original URL
- State: closed
- Created a year ago
- Reactions: 2
- Comments: 15 (7 by maintainers)
Commits related to this issue
- Reimplement stream cancellation (#52281) ### What? This reimplements our stream cancellation code for a few more cases: 1. Adds support in all stream-returning APIs 2. Fixes cancellation detecti... — committed to vercel/next.js by jridgewell a year ago
- Reimplement stream cancellation (#52281) ### What? This reimplements our stream cancellation code for a few more cases: 1. Adds support in all stream-returning APIs 2. Fixes cancellation detecti... — committed to Strift/next.js by jridgewell a year ago
@ijjk @jridgewell I don’t think the issue is fixed. I’ve updated my example to use 13.4.13 but I still see the same issue. Here is also the @jridgewell’s updated version which also shows that it’s not fixed
When invoking the response piping in the Node server, special attention should be paid to the issue of backpressure.
I highly recommend using the node Readable.from(iterable) method to obtain the readable stream, and then using the node stream.pipe method to pipe the readable stream to the outgoing stream.
If this occurs on the edge, simply employ the approach utilized in the
edge-runtime
. It also takes into account the issue of back pressure by actively monitoring the drain event from the node res.This will also provide support for user abortion since the pipe function listens for the underlying response close event and will handle any error issues appropriately.
@jridgewell