Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trigger error for stream on client when it is not finished as expected #65798

Merged
merged 3 commits into from
May 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions packages/next/src/client/app-index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ function nextServerDataCallback(
}
}

function isStreamErrorOrUnfinished(ctr: ReadableStreamDefaultController) {
// If `desiredSize` is null, it means the stream is closed or errored. If it is lower than 0, the stream is still unfinished.
return ctr.desiredSize === null || ctr.desiredSize < 0
}

// There might be race conditions between `nextServerDataRegisterWriter` and
// `DOMContentLoaded`. The former will be called when React starts to hydrate
// the root, the latter will be called when the DOM is fully loaded.
Expand All @@ -104,7 +109,15 @@ function nextServerDataRegisterWriter(ctr: ReadableStreamDefaultController) {
ctr.enqueue(typeof val === 'string' ? encoder.encode(val) : val)
})
if (initialServerDataLoaded && !initialServerDataFlushed) {
ctr.close()
if (isStreamErrorOrUnfinished(ctr)) {
ctr.error(
new Error(
'The connection to the page was unexpectedly closed, possibly due to the stop button being clicked, loss of Wi-Fi, or an unstable internet connection.'
)
)
} else {
ctr.close()
}
initialServerDataFlushed = true
initialServerDataBuffer = undefined
}
Expand All @@ -122,11 +135,13 @@ const DOMContentLoaded = function () {
}
initialServerDataLoaded = true
}

// It's possible that the DOM is already loaded.
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', DOMContentLoaded, false)
} else {
DOMContentLoaded()
// Delayed in marco task to ensure it's executed later than hydration
setTimeout(DOMContentLoaded)
}

const nextServerDataLoadingGlobal = ((self as any).__next_f =
Expand Down
Loading