Unverified Commit a8e01141 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[unstable_after] fix occasional dev-mode crash in edge runtime pages (#66099)

When hot-reloading an edge runtime page, sometimes we randomly get this:
```
[InvariantError: Invariant: Cannot call onClose on a response that is already sent. This is a bug in Next.js.] {
  name: 'InvariantError'
}
```
and since `unstable_after` relies on `onClose`, no callbacks are called.

I believe this is because `web-server` [calls `res.send()` pretty early
for streaming
responses](https://github.com/vercel/next.js/blob/b9817f83519fdaa7a7fcd4711dfb80aa1e1a2434/packages/next/src/server/web-server.ts#L311),
so `res.sent` becomes `true` even though we're still streaming, and
prevents us from calling `onClose` in the streaming render. It makes
more sense to check the CloseController's `isClosed` instead -- when
that becomes `true`, we _really_ shouldn't call onClose anymore (points
to a bug), but before that it's fine.
parent 49ab6f92
...@@ -137,9 +137,9 @@ export class WebNextResponse extends BaseNextResponse<WritableStream> { ...@@ -137,9 +137,9 @@ export class WebNextResponse extends BaseNextResponse<WritableStream> {
'Cannot call onClose on a WebNextResponse initialized with `trackOnClose = false`' 'Cannot call onClose on a WebNextResponse initialized with `trackOnClose = false`'
) )
} }
if (this.sent) { if (this.closeController.isClosed) {
throw new InvariantError( throw new InvariantError(
'Cannot call onClose on a response that is already sent' 'Cannot call onClose on a WebNextResponse that is already closed'
) )
} }
return this.closeController.onClose(callback) return this.closeController.onClose(callback)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment