Skip to content
Source
Sign inSign up
TanStack/router

fix(router-core): don't tear down SSR state while the response body is still streaming #7591

Openradosek(GitHub profile, opens in a new tab)wants to merge 3 commits intomain fromrefs/pull/7591/headopened

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-coreresult
1.169.01.169.0response 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

  • transformStreamWithRouter claims cleanup ownership when it attaches (serverSsr.claimCleanup()).
  • createRequestHandler skips its fallback cleanup when claimed. The transformed stream already calls serverSsr.cleanup() when consumed, cancelled, errored, or when its lifetime expires, so the transfer is leak-free.
  • The onRenderFinished fast-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 + plain Response): fails with a wiped-listener hang before the fix, passes after.
  • router-core suite: 1180 passed, 3 expected-fail, 0 type errors. react-router renderRouterToStream tests and router-ssr-query-core tests 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. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Review Change Stack

      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

      Layer / File(s)Summary
      onRenderFinished behavior change
      packages/router-core/src/ssr/ssr-server.ts
      Stops early-returning when streamFastPathReserved is true; listeners registered after reservation are added so they run when setRenderFinished() executes.
      Regression test for fast-path listener
      packages/router-core/tests/ssr-server-cleanup.test.ts
      Adds a test that reserves the stream fast path, registers an onRenderFinished listener afterwards, asserts it hasn't run immediately, then calls setRenderFinished() and verifies the listener runs exactly once, followed by cleanup.
      Changeset
      .changeset/cool-streams-close.md
      Adds a changeset noting the patch-level fix: late-registered onRenderFinished listeners now run instead of being dropped, preventing SSR stream hangs and documenting cleanup ownership transferred to transformed streams.

      Sequence Diagram(s)

      sequenceDiagram
        participant SSRServer
        participant RouterSsrQueryIntegration
        participant QueryStream
        RouterSsrQueryIntegration->>SSRServer: reserveStreamFastPath()
        RouterSsrQueryIntegration->>SSRServer: onRenderFinished(register close callback)
        SSRServer->>QueryStream: setRenderFinished() (later)
        SSRServer->>RouterSsrQueryIntegration: invoke registered callback
        RouterSsrQueryIntegration->>QueryStream: close()

      Estimated code review effort

      🎯 3 (Moderate) | ⏱️ ~20 minutes

      • TanStack/router#7497: Related earlier streaming lifecycle changes touching createRequestHandler and ssr-server that overlap with this fix.

      Suggested labels

      package: router-core

      Suggested reviewers

      • schiller-manuel

      Poem

      A rabbit found a stalled stream, Where quiet listeners lost their gleam. It nudged the fast path, gave a hop, Now late listeners run — no stop. 🐇✨

      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
      Title check✅ PassedThe title accurately reflects the main fix: preventing SSR state teardown while response body streams, addressing the core issue of premature cleanup.
      Linked Issues check✅ PassedThe PR addresses all five objectives from #7529: identifies root cause of dropped listeners, restores listener behavior by removing streamFastPathReserved guard, ensures dehydration cleanup works, eliminates timeout hang, and maintains compatibility.
      Out of Scope Changes check✅ PassedAll changes are directly scoped to fixing the SSR streaming regression: listener registration fix, cleanup ownership transfer via claimCleanup, and regression test verification.
      ✏️ Tip: You can configure your own custom pre-merge checks in the settings.
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

      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
      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    2. 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.md
      • packages/router-core/src/ssr/ssr-server.ts
      • packages/router-core/tests/ssr-server-cleanup.test.ts
      ✅ Files skipped from review due to trivial changes (1)
      • .changeset/cool-streams-close.md
    3. radosek(GitHub profile, opens in a new tab) changed the title

    4. radosek(GitHub profile, opens in a new tab)commented

      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 on 1.169.0 with identical app code). Tracing it corrected the root cause — premature cleanup() from createRequestHandler's finally, 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

Sign in to join this conversation.