Skip to content

Commit

Permalink
[unstable_after] fix occasional dev-mode crash in edge runtime pages (#…
Browse files Browse the repository at this point in the history
…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.
  • Loading branch information
lubieowoce committed May 22, 2024
1 parent 49ab6f9 commit a8e0114
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions packages/next/src/server/base-http/web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,9 @@ export class WebNextResponse extends BaseNextResponse<WritableStream> {
'Cannot call onClose on a WebNextResponse initialized with `trackOnClose = false`'
)
}
if (this.sent) {
if (this.closeController.isClosed) {
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)
Expand Down

0 comments on commit a8e0114

Please sign in to comment.