fix(router-core): don't tear down SSR state while the response body is still streaming #7591
main fromrefs/pull/7591/head·opened Fixes #7529.
Deterministic reproduction (as requested)#
Repo: https://github.com/radosek/tanstack-7529-repro — live demo (hangs on every request): https://tanstack-7529-repro.radosek.workers.dev/
Same app code, only the version changes:
@tanstack/react-router | @tanstack/router-core | result |
|---|---|---|
1.169.0 | 1.169.0 | response completes in ~3 ms |
1.170.15 (latest) | 1.171.13 (latest) | every request hangs — shell + dehydration chunk arrive, </body></html> and the router module scripts never do, until the ~60 s serialization timeout |
@tanstack/react-router-ssr-query@1.167.1 (latest) in both cases. The entry server is the body of v1.169.0's own renderRouterToStream (the renderToReadableStream branch), inlined verbatim: transformReadableStreamWithRouter(router, stream) + new Response(responseStream, …).
Root cause (instrumented trace against router-core@1.171.13)#
1. onRenderFinished registered OK (listeners=1) ← ssr-query's close listener, during dehydrate()
2. reserveStreamFastPath returns false ← transform takes the main stream path
3. cleanup() wipes renderFinishedListeners=1, ← createRequestHandler's `finally`,
serializationFinishedListeners=1 while the body is STILL STREAMING
4. ssr-query teardown closes the query stream ← via onCleanup
5. setRenderFinished finds listeners=0 ← close listener is gone, completion signals destroyed
createRequestHandler changed semantics: in v1.169.0, once the callback was invoked the handler never cleaned up (cbWillCleanup = true before cb()), so a plain Response was safe. In v1.171.x, cleanup is deferred only when the callback's return value is wrapped by createSsrStreamResponse — an API that did not exist in v1.169.0 — so the same code now triggers cleanup() while the body is still streaming, wiping the listeners the stream transform waits on.
Fix#
transformStreamWithRouterclaims cleanup ownership when it attaches (serverSsr.claimCleanup()).createRequestHandlerskips its fallback cleanup when claimed. The transformed stream already callsserverSsr.cleanup()when consumed, cancelled, errored, or when its lifetime expires, so the transfer is leak-free.- The
onRenderFinishedfast-path guard relaxation from the original PR is kept (covered by its own unit test).
Verification#
- New regression test reproduces the production path (
createRequestHandler+transformStreamWithRouter+ plainResponse): fails with a wiped-listener hang before the fix, passes after. router-coresuite: 1180 passed, 3 expected-fail, 0 type errors.react-routerrenderRouterToStreamtests androuter-ssr-query-coretests pass.- The reproduction app, patched with this fix against the broken combo (
react-router@1.170.15), completes in ~3 ms instead of hanging.
Summary by CodeRabbit#
Bug Fixes
- SSR streaming: listeners added after the stream fast-path reservation now fire when the stream ends, and stream-owned cleanup is respected so fallback cleanup is skipped while streaming—preventing premature teardown and ensuring responses complete reliably.
Tests
- Added a regression test verifying late-registered listeners run and cleanup occurs correctly in fast-path SSR streaming.
- 1
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@packages/router-core/src/ssr/ssr-server.ts`: - Line 640: The single-line guard "if (cleanupStarted) return" must use braces to comply with the TypeScript coding guideline; locate the conditional using the cleanupStarted variable (in the SSR shutdown/cleanup routine where cleanupStarted is checked) and replace the single-line form with a braced block (e.g., if (cleanupStarted) { return; }) so the control statement always uses curly braces.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
265c1e99-50a2-427c-b3ff-819c14e0feca📥 Commits
Reviewing files that changed from the base of the PR and between ae9d550b8520ec6d93c0e93ecf3d5ed99a505328 and ad107d257f6b157a8fe86ac6e647ed5c44db8886.
📒 Files selected for processing (3)
.changeset/cool-streams-close.mdpackages/router-core/src/ssr/ssr-server.tspackages/router-core/tests/ssr-server-cleanup.test.ts
✅ Files skipped from review due to trivial changes (1)
- .changeset/cool-streams-close.md
packages/router-core/src/ssr/ssr-server.ts line 647Resolvedby radosek(GitHub profile, opens in a new tab)@@ -637,4 +637,4 @@637637 return () => removeListener(injectedHtmlListeners, listener)638638 },639639 onRenderFinished: (listener) => {640- if (cleanupStarted || streamFastPathReserved) return640+ if (cleanupStarted) return⚠️ Potential issue | 🔴 Critical | ⚡ Quick win
Add curly braces for the
ifstatement.The single-line
ifstatement violates the coding guideline requiring curly braces for all control statements in TypeScript files.✅ Proposed fix
- onRenderFinished: (listener) => { - if (cleanupStarted) return + onRenderFinished: (listener) => { + if (cleanupStarted) { + return + } // Register even when the fast path is reserved. The fast path still calls📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change647+ onRenderFinished: (listener) => {648+ if (cleanupStarted) {649+ return650+ }651+ // Register even when the fast path is reserved. The fast path still calls🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/router-core/src/ssr/ssr-server.ts` at line 640, The single-line guard "if (cleanupStarted) return" must use braces to comply with the TypeScript coding guideline; locate the conditional using the cleanupStarted variable (in the SSR shutdown/cleanup routine where cleanupStarted is checked) and replace the single-line form with a braced block (e.g., if (cleanupStarted) { return; }) so the control statement always uses curly braces.Source: Coding guidelines
Declining: this matches the established style in
ssr-server.ts, which has ~25 single-lineif (...) returnguards (the adjacentinjectHtml,injectScript,onSerializationFinished,onCleanup,setRenderFinishedall use the same form). There is nocurlyrule in the repo eslint config, so this is a CodeRabbit-default guideline rather than a project one. Also, this exact line predates the PR — the diff only removed the|| streamFastPathReservedcondition. Adding braces here would make it inconsistent with its siblings.@radosek, understood and acknowledged — the single-lineif (...) returnform is the established convention throughoutssr-server.tsand isn't enforced by the project's ESLint config. I'll stop flagging this pattern in this file.🐇 (・・)_
✏️ Learnings added
Learnt from: radosek Repo: TanStack/router PR: 7591 File: packages/router-core/src/ssr/ssr-server.ts:640-640 Timestamp: 2026-06-09T12:15:34.319Z Learning: In `packages/router-core/src/ssr/ssr-server.ts` (TanStack Router, TypeScript), the established code style uses single-line `if (condition) return` guards (without curly braces) for early-exit checks — approximately 25 such guards exist throughout the file (e.g., in `injectHtml`, `injectScript`, `onRenderFinished`, `onSerializationFinished`, `onCleanup`, `setRenderFinished`). There is no `curly` rule in the project's ESLint config. Do not flag these single-line guards as style violations; requiring braces here would make the code inconsistent with its siblings and is not a project-enforced rule.Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
🧠 Learnings used
Learnt from: schiller-manuel Repo: TanStack/router PR: 7503 File: e2e/vue-start/basic/src/routes/__root.tsx:71-73 Timestamp: 2026-05-29T00:17:44.833Z Learning: For TanStack Router / TanStack Start projects, when reviewing `useRouterState` usage with a `select` callback (e.g., `useRouterState({ select: (state) => ... })`), do not require an explicit type annotation for the `select` callback parameter. TypeScript should infer the correct parameter type from TanStack Router/Start’s generic definitions. Only flag type-annotation issues if the inferred type is `any` (or otherwise fails type safety), since the intended pattern relies on inference rather than manual annotations.not happening until https://github.com/TanStack/router/issues/7529 has a reproducer
radosek(GitHub profile, opens in a new tab) changed the title
Reproducer is up: https://github.com/radosek/tanstack-7529-repro (live: https://tanstack-7529-repro.radosek.workers.dev/ — hangs on every request on latest
react-router+react-router-ssr-query, completes in ~3 ms on1.169.0with identical app code). Tracing it corrected the root cause — prematurecleanup()fromcreateRequestHandler'sfinally, not the fast-path guard — details in https://github.com/TanStack/router/issues/7529#issuecomment-4695422561. PR updated with the ownership fix + a regression test that reproduces the production path.@schiller-manuel
radosek(GitHub profile, opens in a new tab) linked this to fix #7529
Sign in to join this conversation.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
eb67cd21-6a07-4d1c-a33c-01e87d6e9c40📥 Commits
Reviewing files that changed from the base of the PR and between ea60ebeb697d4dd563a4196f38a243c659841b0e and 54c7bec0def2165fc35517ac29ba6540d0a676ab.
📒 Files selected for processing (1)
.changeset/cool-streams-close.md📝 Walkthrough
Walkthrough#
Fixes an SSR streaming regression: onRenderFinished no longer drops listeners registered after the stream fast path is reserved; such listeners are retained and invoked (verified by a regression test and documented in a changeset).
Changes#
SSR Listener Execution Fix
packages/router-core/src/ssr/ssr-server.tsstreamFastPathReservedis true; listeners registered after reservation are added so they run whensetRenderFinished()executes.packages/router-core/tests/ssr-server-cleanup.test.tsonRenderFinishedlistener afterwards, asserts it hasn't run immediately, then callssetRenderFinished()and verifies the listener runs exactly once, followed by cleanup..changeset/cool-streams-close.mdonRenderFinishedlisteners now run instead of being dropped, preventing SSR stream hangs and documenting cleanup ownership transferred to transformed streams.Sequence Diagram(s)#
Estimated code review effort#
🎯 3 (Moderate) | ⏱️ ~20 minutes
Possibly related PRs#
Suggested labels#
package: router-coreSuggested reviewers#
Poem#
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
#7529: identifies root cause of dropped listeners, restores listener behavior by removing streamFastPathReserved guard, ensures dehydration cleanup works, eliminates timeout hang, and maintains compatibility.✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share