Skip to content

fix(router-core): flush buffered scripts before closing SSR stream#7352

Open
roduyemi wants to merge 2 commits intoTanStack:mainfrom
roduyemi:missing-scripts
Open

fix(router-core): flush buffered scripts before closing SSR stream#7352
roduyemi wants to merge 2 commits intoTanStack:mainfrom
roduyemi:missing-scripts

Conversation

@roduyemi
Copy link
Copy Markdown
Contributor

@roduyemi roduyemi commented May 6, 2026

Streaming scripts ($_TSR.e() and deferred data resolvers) are silently dropped when serialisation finishes before the HTML stream is processed.

Fixes #7349

Two root causes:

  1. ScriptBuffer.enqueue() and liftBarrier() defer injection via queueMicrotask which means cleanup() runs synchronously before the microtask fires
  2. The fast-exit path in transformStreamWithRouter never calls takeBufferedHtml() after setRenderFinished()

Changes

  • Makes ScriptBuffer.enqueue() and liftBarrier() synchronous
  • Adds flushScripts() to ServerSsr and calls it in tryFinish()
  • Flushes buffered HTML in the fast-exit path after setRenderFinished()
  • Moves liftScriptBarrier() after flushPendingRouterHtml() to ensure correct ordering
  • Adds unit tests for ScriptBuffer

Summary by CodeRabbit

  • New Features

    • Added flushScripts() method to enable manual flushing of queued server-side rendering scripts.
  • Improvements

    • Enhanced script buffering and injection behavior during server-side rendering for better script execution control.
    • Refined script barrier handling in streaming scenarios to ensure proper timing and injection order.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 6, 2026

📝 Walkthrough

Walkthrough

This PR fixes missing scripts during SSR streaming by adding a public flushScripts() API and deferring script barrier lifting until safe points after HTML finalization. Scripts are now injected immediately when barriers lift, and final buffered HTML is drained before cleanup.

Changes

SSR Script Injection and Barrier Deferral

Layer / File(s) Summary
Public API
packages/router-core/src/ssr/ssr-server.ts (lines 24–27)
Add flushScripts(): void method to ServerSsr interface augmentation.
ScriptBuffer Behavior
packages/router-core/src/ssr/ssr-server.ts (lines 89–101)
Modify enqueue() to immediately inject buffered scripts when barrier is already lifted; refactor liftBarrier() to inject synchronously without microtask scheduling.
flushScripts Implementation
packages/router-core/src/ssr/ssr-server.ts (line 507–509)
Implement flushScripts() as a public method forwarding to scriptBuffer.flush().
Stream Transform Fast-Path
packages/router-core/src/ssr/transformStreamWithRouter.ts (lines 192–197)
Retrieve final buffered HTML via takeBufferedHtml(), enqueue it, and clean up safely instead of early exit on closed state.
Stream Transform Finalization
packages/router-core/src/ssr/transformStreamWithRouter.ts (lines 339–343)
Call router.serverSsr?.flushScripts() before finishing to emit all pending SSR scripts.
Deferred Barrier Lifting
packages/router-core/src/ssr/transformStreamWithRouter.ts (lines 413–451)
Defer TSR script barrier lifting until safe points: mark streamBarrierLifted flag on barrier ID detection, then conditionally lift after body closing tags and closing tag boundaries to preserve injection order.
Test Coverage
packages/router-core/tests/script-buffer.test.ts
Add helper function buildRouter() and two integration tests validating synchronous script injection when barrier lifts after serialization and that scripts are not dropped on immediate cleanup after setRenderFinished().

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 Hop, skip, and script injection flow,
Barriers deferred where fast streams go,
No more lost scripts when rendering's done,
Flushed and ready—the final hop's won!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.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 name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: flushing buffered scripts before closing the SSR stream, which directly addresses the root cause of issue #7349.
Linked Issues check ✅ Passed The pull request fully addresses all coding requirements from issue #7349: makes ScriptBuffer synchronous, adds flushScripts() method, flushes buffered HTML in fast-exit path, and includes comprehensive unit tests.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing the missing scripts issue: modifications to SSR script buffering, barrier lifting, streaming transform logic, and tests validating the fix.

✏️ 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.

@roduyemi roduyemi changed the title Missing scripts @roduyemi fix(router-core): flush buffered scripts before closing SSR stream May 6, 2026
@nx-cloud
Copy link
Copy Markdown
Contributor

nx-cloud Bot commented May 6, 2026

View your CI Pipeline Execution ↗ for commit 1e2ff8d

Command Status Duration Result
nx affected --targets=test:eslint,test:unit,tes... ❌ Failed 7m 55s View ↗
nx run-many --target=build --exclude=examples/*... ✅ Succeeded 1m 47s View ↗

☁️ Nx Cloud last updated this comment at 2026-05-06 10:18:14 UTC

@roduyemi roduyemi changed the title @roduyemi fix(router-core): flush buffered scripts before closing SSR stream fix(router-core): flush buffered scripts before closing SSR stream May 6, 2026
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 6, 2026

Bundle Size Benchmarks

  • Commit: ee96e25d1487
  • Measured at: 2026-05-06T10:11:17.774Z
  • Baseline source: history:35e88f04996d
  • Dashboard: bundle-size history
Scenario Current (gzip) Delta vs baseline Raw Brotli Trend
react-router.minimal 87.15 KiB 0 B (0.00%) 273.94 KiB 75.70 KiB ▅▅▅▅▅▅▅▅▅▅▅
react-router.full 90.68 KiB 0 B (0.00%) 285.45 KiB 78.71 KiB ▅▅▅▅▅▅▅▅▅▅▅
solid-router.minimal 35.38 KiB 0 B (0.00%) 106.25 KiB 31.81 KiB ▅▅▅▅▅▅▅▅▅▅▅
solid-router.full 40.10 KiB 0 B (0.00%) 120.46 KiB 36.04 KiB ▅▅▅▅▅▅▅▅▅▅▅
vue-router.minimal 53.15 KiB 0 B (0.00%) 151.39 KiB 47.73 KiB ▅▅▅▅▅▅▅▅▅▅▅
vue-router.full 58.28 KiB 0 B (0.00%) 167.56 KiB 52.18 KiB ▅▅▅▅▅▅▅▅▅▅▅
react-start.minimal 101.84 KiB 0 B (0.00%) 322.38 KiB 88.03 KiB ▁▁▁▁▁▁▁▁▁▁█
react-start.full 105.27 KiB 0 B (0.00%) 332.71 KiB 91.00 KiB ▁▁▁▁▁▁▁▁▁▁█
react-start.rsbuild.minimal 99.43 KiB 0 B (0.00%) 316.76 KiB 85.51 KiB ▁▁▁▁▁▁▁▁▁▁█
react-start.rsbuild.full 102.72 KiB 0 B (0.00%) 327.19 KiB 88.31 KiB ▁▁▁▁▁▁▁▁▁▁█
solid-start.minimal 49.48 KiB 0 B (0.00%) 152.36 KiB 43.69 KiB ▁▁▁▁▁▁▁▁▁▁█
solid-start.full 55.27 KiB 0 B (0.00%) 169.27 KiB 48.60 KiB ▁▁▁▁▁▁▁▁▁▁█

Trend sparkline is historical gzip bytes ending with this PR measurement; lower is better.

@pkg-pr-new
Copy link
Copy Markdown

pkg-pr-new Bot commented May 6, 2026

More templates

@tanstack/arktype-adapter

npm i https://pkg.pr.new/@tanstack/arktype-adapter@7352

@tanstack/eslint-plugin-router

npm i https://pkg.pr.new/@tanstack/eslint-plugin-router@7352

@tanstack/eslint-plugin-start

npm i https://pkg.pr.new/@tanstack/eslint-plugin-start@7352

@tanstack/history

npm i https://pkg.pr.new/@tanstack/history@7352

@tanstack/nitro-v2-vite-plugin

npm i https://pkg.pr.new/@tanstack/nitro-v2-vite-plugin@7352

@tanstack/react-router

npm i https://pkg.pr.new/@tanstack/react-router@7352

@tanstack/react-router-devtools

npm i https://pkg.pr.new/@tanstack/react-router-devtools@7352

@tanstack/react-router-ssr-query

npm i https://pkg.pr.new/@tanstack/react-router-ssr-query@7352

@tanstack/react-start

npm i https://pkg.pr.new/@tanstack/react-start@7352

@tanstack/react-start-client

npm i https://pkg.pr.new/@tanstack/react-start-client@7352

@tanstack/react-start-rsc

npm i https://pkg.pr.new/@tanstack/react-start-rsc@7352

@tanstack/react-start-server

npm i https://pkg.pr.new/@tanstack/react-start-server@7352

@tanstack/router-cli

npm i https://pkg.pr.new/@tanstack/router-cli@7352

@tanstack/router-core

npm i https://pkg.pr.new/@tanstack/router-core@7352

@tanstack/router-devtools

npm i https://pkg.pr.new/@tanstack/router-devtools@7352

@tanstack/router-devtools-core

npm i https://pkg.pr.new/@tanstack/router-devtools-core@7352

@tanstack/router-generator

npm i https://pkg.pr.new/@tanstack/router-generator@7352

@tanstack/router-plugin

npm i https://pkg.pr.new/@tanstack/router-plugin@7352

@tanstack/router-ssr-query-core

npm i https://pkg.pr.new/@tanstack/router-ssr-query-core@7352

@tanstack/router-utils

npm i https://pkg.pr.new/@tanstack/router-utils@7352

@tanstack/router-vite-plugin

npm i https://pkg.pr.new/@tanstack/router-vite-plugin@7352

@tanstack/solid-router

npm i https://pkg.pr.new/@tanstack/solid-router@7352

@tanstack/solid-router-devtools

npm i https://pkg.pr.new/@tanstack/solid-router-devtools@7352

@tanstack/solid-router-ssr-query

npm i https://pkg.pr.new/@tanstack/solid-router-ssr-query@7352

@tanstack/solid-start

npm i https://pkg.pr.new/@tanstack/solid-start@7352

@tanstack/solid-start-client

npm i https://pkg.pr.new/@tanstack/solid-start-client@7352

@tanstack/solid-start-server

npm i https://pkg.pr.new/@tanstack/solid-start-server@7352

@tanstack/start-client-core

npm i https://pkg.pr.new/@tanstack/start-client-core@7352

@tanstack/start-fn-stubs

npm i https://pkg.pr.new/@tanstack/start-fn-stubs@7352

@tanstack/start-plugin-core

npm i https://pkg.pr.new/@tanstack/start-plugin-core@7352

@tanstack/start-server-core

npm i https://pkg.pr.new/@tanstack/start-server-core@7352

@tanstack/start-static-server-functions

npm i https://pkg.pr.new/@tanstack/start-static-server-functions@7352

@tanstack/start-storage-context

npm i https://pkg.pr.new/@tanstack/start-storage-context@7352

@tanstack/valibot-adapter

npm i https://pkg.pr.new/@tanstack/valibot-adapter@7352

@tanstack/virtual-file-routes

npm i https://pkg.pr.new/@tanstack/virtual-file-routes@7352

@tanstack/vue-router

npm i https://pkg.pr.new/@tanstack/vue-router@7352

@tanstack/vue-router-devtools

npm i https://pkg.pr.new/@tanstack/vue-router-devtools@7352

@tanstack/vue-router-ssr-query

npm i https://pkg.pr.new/@tanstack/vue-router-ssr-query@7352

@tanstack/vue-start

npm i https://pkg.pr.new/@tanstack/vue-start@7352

@tanstack/vue-start-client

npm i https://pkg.pr.new/@tanstack/vue-start-client@7352

@tanstack/vue-start-server

npm i https://pkg.pr.new/@tanstack/vue-start-server@7352

@tanstack/zod-adapter

npm i https://pkg.pr.new/@tanstack/zod-adapter@7352

commit: 1e2ff8d

@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented May 6, 2026

Merging this PR will not alter performance

✅ 6 untouched benchmarks


Comparing roduyemi:missing-scripts (1e2ff8d) with main (35e88f0)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (ee96e25) during the generation of this report, so 35e88f0 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report.

@roduyemi roduyemi marked this pull request as ready for review May 6, 2026 10:32
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
packages/router-core/tests/script-buffer.test.ts (1)

46-48: 💤 Low value

Optional: replace fixed-timeout wait with onSerializationFinished subscription for determinism.

The 50ms setTimeout is generous but can become flaky on busy CI runners. Subscribing to the existing onSerializationFinished event (or awaiting a promise that resolves on it) makes the assertion deterministic and faster. The same applies to lines 81–82 in the second test.

Proposed change
-    // Wait for deferred promise + crossSerializeStream.onDone
-    await new Promise((r) => setTimeout(r, 50))
-    expect(router.serverSsr!.isSerializationFinished()).toBe(true)
+    // Wait until serialization completes deterministically
+    await new Promise<void>((resolve) => {
+      const unsub = router.subscribe('onSerializationFinished', () => {
+        unsub()
+        resolve()
+      })
+    })
+    expect(router.serverSsr!.isSerializationFinished()).toBe(true)
🤖 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/tests/script-buffer.test.ts` around lines 46 - 48,
Replace the fixed 50ms timeout with a deterministic wait for the serialization
completion event: subscribe to router.serverSsr!.onSerializationFinished (or
await a promise that resolves when that event fires) before asserting
router.serverSsr!.isSerializationFinished(); do the same replacement for the
other occurrence in the second test (lines around the second timeout) so tests
no longer rely on setTimeout and become deterministic and faster.
packages/router-core/src/ssr/ssr-server.ts (1)

112-144: 💤 Low value

Optional: collapse flush() and injectBufferedScripts() to remove duplication.

The two methods perform nearly identical work — takeAll() + injectScript(). Their only meaningful differences are early-return predicates. Consolidating into a single private helper (with a force or respectBarrier flag) would reduce drift risk.

Sketch
private inject(respectBarrier: boolean) {
  if (this._cleanedUp) return
  if (respectBarrier && !this._scriptBarrierLifted) return
  if (this._queue.length === 0) return
  const scriptsToInject = this.takeAll()
  if (scriptsToInject && this.router?.serverSsr) {
    this.router.serverSsr.injectScript(scriptsToInject)
  }
}

flush() { this.inject(true) }
injectBufferedScripts() { this.inject(false) }
🤖 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` around lines 112 - 144, The
flush() and injectBufferedScripts() methods duplicate logic (calling takeAll()
and router.serverSsr.injectScript) with only different early-return predicates;
refactor by creating a private helper (e.g., inject(respectBarrier: boolean))
that centralizes the checks: return if this._cleanedUp, if respectBarrier &&
!this._scriptBarrierLifted, and if this._queue.length === 0, then call takeAll()
and, if result and this.router?.serverSsr, call
this.router.serverSsr.injectScript(scriptsToInject); replace flush() with
this.inject(true) and injectBufferedScripts() with this.inject(false) to remove
duplication while keeping semantics.
packages/router-core/src/ssr/transformStreamWithRouter.ts (1)

437-451: 💤 Low value

Deferred liftScriptBarrier() ordering is correct, with a minor redundancy.

Lifting the barrier after flushPendingRouterHtml() is right: it guarantees pending router HTML is emitted before any scripts queued post-lift get injected. Note that once the local streamBarrierLifted becomes true, it stays true, so every subsequent closing-tag boundary will re-call liftScriptBarrier(). The call is idempotent (guarded by _scriptBarrierLifted), so this is harmless — just a tiny bit of repeated work. Optional: short-circuit locally after the first successful lift if you want to avoid the extra 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/transformStreamWithRouter.ts` around lines 437 -
451, The code repeatedly calls router.serverSsr?.liftScriptBarrier() whenever
streamBarrierLifted is true even though the lift is idempotent; short-circuit
after the first lift by checking and setting a local guard so subsequent
branches skip the call. Modify the block that currently checks
streamBarrierLifted (near findLastClosingTagEnd logic in
transformStreamWithRouter) to only invoke router.serverSsr?.liftScriptBarrier()
once: e.g., add or flip a local boolean (using the existing streamBarrierLifted
or a new local like localBarrierLifted) to ensure liftScriptBarrier() and its
setter run only on the first pass, keeping flushPendingRouterHtml(),
safeEnqueue(), and findLastClosingTagEnd usage unchanged.
🤖 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.

Nitpick comments:
In `@packages/router-core/src/ssr/ssr-server.ts`:
- Around line 112-144: The flush() and injectBufferedScripts() methods duplicate
logic (calling takeAll() and router.serverSsr.injectScript) with only different
early-return predicates; refactor by creating a private helper (e.g.,
inject(respectBarrier: boolean)) that centralizes the checks: return if
this._cleanedUp, if respectBarrier && !this._scriptBarrierLifted, and if
this._queue.length === 0, then call takeAll() and, if result and
this.router?.serverSsr, call
this.router.serverSsr.injectScript(scriptsToInject); replace flush() with
this.inject(true) and injectBufferedScripts() with this.inject(false) to remove
duplication while keeping semantics.

In `@packages/router-core/src/ssr/transformStreamWithRouter.ts`:
- Around line 437-451: The code repeatedly calls
router.serverSsr?.liftScriptBarrier() whenever streamBarrierLifted is true even
though the lift is idempotent; short-circuit after the first lift by checking
and setting a local guard so subsequent branches skip the call. Modify the block
that currently checks streamBarrierLifted (near findLastClosingTagEnd logic in
transformStreamWithRouter) to only invoke router.serverSsr?.liftScriptBarrier()
once: e.g., add or flip a local boolean (using the existing streamBarrierLifted
or a new local like localBarrierLifted) to ensure liftScriptBarrier() and its
setter run only on the first pass, keeping flushPendingRouterHtml(),
safeEnqueue(), and findLastClosingTagEnd usage unchanged.

In `@packages/router-core/tests/script-buffer.test.ts`:
- Around line 46-48: Replace the fixed 50ms timeout with a deterministic wait
for the serialization completion event: subscribe to
router.serverSsr!.onSerializationFinished (or await a promise that resolves when
that event fires) before asserting router.serverSsr!.isSerializationFinished();
do the same replacement for the other occurrence in the second test (lines
around the second timeout) so tests no longer rely on setTimeout and become
deterministic and faster.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 511bcafb-71f1-4b86-8bcd-d9b61cdd9638

📥 Commits

Reviewing files that changed from the base of the PR and between ee96e25 and 1e2ff8d.

📒 Files selected for processing (3)
  • packages/router-core/src/ssr/ssr-server.ts
  • packages/router-core/src/ssr/transformStreamWithRouter.ts
  • packages/router-core/tests/script-buffer.test.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Missing scripts during streaming

1 participant