Repository navigation
fix(vue): batch streamed head updates via self-deleting inline scripts - #752
Conversation
📝 WalkthroughWalkthroughRefactors Vue streaming SSR: removes the in-tree Changes
Sequence Diagram(s)sequenceDiagram
participant Server
participant StreamWrapper
participant TemplatePrep as prepareStreamingTemplate
participant Browser
Server->>StreamWrapper: call wrapStream(appStream, vueHead, template)
StreamWrapper->>TemplatePrep: split template at outlet marker
TemplatePrep-->>StreamWrapper: shell + end
StreamWrapper->>Browser: enqueue shell
alt upstream chunk arrives
StreamWrapper->>Browser: forward chunk
StreamWrapper->>Browser: enqueue inline self-deleting script (window.__unhead__.push(...))
end
StreamWrapper->>Browser: enqueue end
Browser->>Browser: script executes and removes itself before hydration
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 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. Comment |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/unhead/src/stream/server.ts (1)
260-286:⚠️ Potential issue | 🟠 MajorInterleaving script patches between chunks risks producing malformed HTML when chunk boundaries split mid-tag.
flushPatchis enqueued immediately after every value read from the framework stream. Verification confirms that Vue 3'srenderToWebStreamdoes not guarantee chunk boundaries align with HTML tag boundaries—chunks can split mid-tag or mid-attribute. If a chunk ends with<div class="aand the next begins withbc">, interleaving a<script>${patch};document.currentScript.remove()</script>between them produces invalid HTML:<div class="a<script>...</script>bc">.To mitigate:
- Coalesce pending
head.entriesand only emit the patch whenrenderSSRHeadSuspenseChunkhas content to flush (already true).- Document the implementation's implicit "chunks must be tag-aligned" contract, or buffer chunks at the stream wrapper layer to ensure boundaries land between complete tokens before triggering flushes.
- Verify that other frameworks (Solid, Svelte, etc.) routed through
WebStreamableHeadContext.wrapStreamalso have this chunk-splitting behavior.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/unhead/src/stream/server.ts` around lines 260 - 286, The current approach calls flushPatch immediately after each controller.enqueue(value), which can split HTML tags across chunks and produce malformed markup; update the streaming logic around flushPatch/renderSSRHeadSuspenseChunk so you buffer chunk data (e.g., accumulate into a pending buffer between controller.enqueue calls) and only inject the script patch when you can guarantee a safe boundary (for example when the buffered data ends with a complete token like '>' or any other heuristic you choose), then flush the buffered bytes through controller.enqueue followed by the script patch; apply this change in the start(reader loop) where controller.enqueue(value) and flushPatch are invoked and ensure the final flushPatch after the reader completes also flushes any remaining buffered data; also ensure WebStreamableHeadContext.wrapStream users (renderSSRHeadSuspenseChunk/flushPatch) are compatible with this buffering approach.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Outside diff comments:
In `@packages/unhead/src/stream/server.ts`:
- Around line 260-286: The current approach calls flushPatch immediately after
each controller.enqueue(value), which can split HTML tags across chunks and
produce malformed markup; update the streaming logic around
flushPatch/renderSSRHeadSuspenseChunk so you buffer chunk data (e.g., accumulate
into a pending buffer between controller.enqueue calls) and only inject the
script patch when you can guarantee a safe boundary (for example when the
buffered data ends with a complete token like '>' or any other heuristic you
choose), then flush the buffered bytes through controller.enqueue followed by
the script patch; apply this change in the start(reader loop) where
controller.enqueue(value) and flushPatch are invoked and ensure the final
flushPatch after the reader completes also flushes any remaining buffered data;
also ensure WebStreamableHeadContext.wrapStream users
(renderSSRHeadSuspenseChunk/flushPatch) are compatible with this buffering
approach.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 90f23753-02ad-4a90-8085-0e5bbc49eb2f
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (13)
examples/vite-ssr-vue-streaming/index.htmlexamples/vite-ssr-vue-streaming/src/App.vueexamples/vite-ssr-vue-streaming/src/entry-client.tsexamples/vite-ssr-vue-streaming/tests/streaming.spec.tspackages/unhead/src/stream/server.tspackages/unhead/src/stream/vite.tspackages/vue/build.config.tspackages/vue/package.jsonpackages/vue/src/stream/client.tspackages/vue/src/stream/server.tspackages/vue/src/stream/vite.tspackages/vue/test/streaming.test.tspackages/vue/test/vite-plugin.test.ts
💤 Files with no reviewable changes (3)
- examples/vite-ssr-vue-streaming/src/entry-client.ts
- packages/vue/package.json
- packages/vue/src/stream/client.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/vue/src/stream/server.ts (1)
107-117: The namedwrapStreamre-export fromunhead/stream/serverhas a different signature than the Vue-specific version and creates a footgun.The core
wrapStream(head, stream, template)and Vue-specificwrapStream(stream, template)have incompatible signatures. Users importing the named export would get the core version, causing a runtime error when called with the Vue pattern. Rename the re-export (e.g.,coreWrapStream), remove it if unused, or document the distinction clearly. Current codebase avoids the issue by consistently usingcreateStreamableHead().wrapStream.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/vue/src/stream/server.ts` around lines 107 - 117, The named re-export wrapStream from 'unhead/stream/server' conflicts with the Vue-specific wrapStream signature and can cause runtime errors; update the export block to either remove the direct wrapStream re-export or rename it (e.g., coreWrapStream) so it won’t shadow the Vue pattern, and adjust any internal imports/uses to call createStreamableHead().wrapStream for Vue usage or coreWrapStream for the unhead core signature; ensure the export list in packages/vue/src/stream/server.ts no longer exposes the incompatible wrapStream name to consumers.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/vue/src/stream/server.ts`:
- Around line 74-89: wrapStream currently injects the streaming template (via
prepareStreamingTemplate and flushPatch) immediately after each ReadableStream
read which can split HTML tags if the source stream (e.g., a transformed/custom
stream) emits arbitrary byte boundaries; update wrapStream to buffer incoming
Uint8Array chunks and only call controller.enqueue and flushPatch when a safe
insertion point is detected (e.g., buffer ends with a complete tag boundary such
as a closing tag delimiter like '>' or a verified '</...>' sequence), falling
back to a maximum buffer size/time flush to avoid stalling; update
prepareStreamingTemplate/flushPatch references accordingly and add an
integration test that uses Vue's renderToWebStream to confirm chunk boundaries
are safe (or add clear JSDoc on wrapStream that only Vue renderToWebStream
output is supported if you choose the simpler documentation approach).
---
Nitpick comments:
In `@packages/vue/src/stream/server.ts`:
- Around line 107-117: The named re-export wrapStream from
'unhead/stream/server' conflicts with the Vue-specific wrapStream signature and
can cause runtime errors; update the export block to either remove the direct
wrapStream re-export or rename it (e.g., coreWrapStream) so it won’t shadow the
Vue pattern, and adjust any internal imports/uses to call
createStreamableHead().wrapStream for Vue usage or coreWrapStream for the unhead
core signature; ensure the export list in packages/vue/src/stream/server.ts no
longer exposes the incompatible wrapStream name to consumers.
🪄 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: 7cb776e6-377a-423a-9f25-39ab560387ae
📒 Files selected for processing (2)
packages/unhead/src/stream/server.tspackages/vue/src/stream/server.ts
Vue streaming relied on an SFC AST transform that injected a `<HeadStream />` component into every template using `useHead` / `useSeoMeta`, plus a symmetric client vnode with `data-allow-mismatch` — heavy plumbing that also needed vue-loader patching on webpack/rspack. Replaced it with per-chunk flushing inside the Vue `wrapStream` wrapper: after each Vue stream chunk, any newly added head entries are emitted as `<script>window.__unhead__.push(...);document.currentScript.remove()</script>`. The script executes during HTML parse (updating the client head state progressively) and removes itself before Vue hydrates, so no `<HeadStream />` vnode or `data-allow-mismatch` workaround is needed. Only safe on Vue because `renderToWebStream` streams chunks in document order per resolved Suspense boundary. React / Solid / Svelte reveal boundaries out-of-order and continue to use in-tree `<HeadStream />`. Drops from `@unhead/vue`: - SFC AST transform in `@unhead/vue/stream/vite` (and the `magic-string`, `oxc-parser`, `oxc-walker` deps) - `HeadStream` component on server + client and the `_shellRendered` coordination flag
1d89d57 to
a292331
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/vue/src/stream/server.ts (1)
82-97: Optional: the trailingflushPatchafter the read loop is redundant.Line 88 already calls
flushPatch(controller)after every successful chunk, and no Vue code path adds new head entries between the final{ done: true }read and thecontroller.close()call.renderSSRHeadSuspenseChunkreturns an empty string whenhead.entries.size === 0, so the extra call on line 95 is a no-op in practice — fine to leave, but can be removed for clarity.♻️ Proposed simplification
} finally { reader.releaseLock() } - flushPatch(controller) controller.enqueue(encoder.encode(end)) controller.close()🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/vue/src/stream/server.ts` around lines 82 - 97, The trailing call to flushPatch(controller) after the read loop is redundant since flushPatch(controller) is already invoked for every chunk inside the loop (see reader.read() loop and flushPatch references); remove the extra flushPatch(controller) that occurs just before controller.enqueue(encoder.encode(end)) and controller.close() so the finalization only enqueues the end marker and closes the controller, leaving reader.releaseLock() and the in-loop flushes intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/vue/src/stream/server.ts`:
- Around line 82-97: The trailing call to flushPatch(controller) after the read
loop is redundant since flushPatch(controller) is already invoked for every
chunk inside the loop (see reader.read() loop and flushPatch references); remove
the extra flushPatch(controller) that occurs just before
controller.enqueue(encoder.encode(end)) and controller.close() so the
finalization only enqueues the end marker and closes the controller, leaving
reader.releaseLock() and the in-loop flushes intact.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 8ca9f499-58b1-4a59-a36c-995c568df530
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (8)
examples/vite-ssr-vue-streaming/tests/streaming.spec.tspackages/vue/build.config.tspackages/vue/package.jsonpackages/vue/src/stream/client.tspackages/vue/src/stream/server.tspackages/vue/src/stream/vite.tspackages/vue/test/streaming.test.tspackages/vue/test/vite-plugin.test.ts
💤 Files with no reviewable changes (2)
- packages/vue/package.json
- packages/vue/src/stream/client.ts
✅ Files skipped from review due to trivial changes (1)
- examples/vite-ssr-vue-streaming/tests/streaming.spec.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/vue/build.config.ts
- packages/vue/test/streaming.test.ts
prepareStreamingTemplate now splits at <!--app-html--> / <!--ssr-outlet-->
when present so streamed app content lands inside the mount container.
Falls back to <body>/</body> splitting when no marker exists.
Without marker support, an `<div id="app">` in the template ended up
after the streamed Vue output, forcing apps to wrap their root component
in a redundant `<div id="app">`. That setup hydrated incorrectly because
`app.mount('#app')` treats `#app` as a container and expects App's root
vnode to be its first child, not the container itself.
- examples/vite-ssr-vue-streaming: add #app container in index.html and
drop the redundant wrapper from App.vue
- streaming.spec.ts: stop filtering hydration warnings (was masking the
bug) and assert on warnings as well as errors
- update stale exports snapshot (HeadStream was removed by the previous
commit on this branch)
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/unhead/src/stream/server.ts (1)
357-363:⚠️ Potential issue | 🟡 MinorStrip the artificial suffix from the tail only.
Line 363 removes the first
</body></html>occurrence. If the template already contains that literal earlier, for example inside an inline script string, this corrupts the template and leaves the artificial suffix inshell.🐛 Proposed fix
+ const artificialShellSuffix = '</body></html>' const shellParsed = parseHtmlForIndexes(`${shellPart}</body></html>`) - const shell = applyHeadToHtml(shellParsed, { + const shellWithInjectedHead = applyHeadToHtml(shellParsed, { htmlAttrs: ssr.htmlAttrs, headTags: bootstrapScript + ssr.headTags, bodyAttrs: ssr.bodyAttrs, bodyTags: '', - }).replace('</body></html>', '') + }) + const shell = shellWithInjectedHead.endsWith(artificialShellSuffix) + ? shellWithInjectedHead.slice(0, -artificialShellSuffix.length) + : shellWithInjectedHead🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/unhead/src/stream/server.ts` around lines 357 - 363, The code currently removes the first occurrence of the artificial suffix by using .replace('</body></html>','') which can corrupt templates if that literal appears earlier; change the logic around shell creation (after parseHtmlForIndexes and applyHeadToHtml where shellParsed, shellPart and shell are used) to strip the artificial suffix only from the tail — detect if the resulting string endsWith('</body></html>') and if so remove that trailing substring (or remove the lastIndexOf occurrence at the string end) instead of a global/first replace so embedded occurrences are preserved.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Outside diff comments:
In `@packages/unhead/src/stream/server.ts`:
- Around line 357-363: The code currently removes the first occurrence of the
artificial suffix by using .replace('</body></html>','') which can corrupt
templates if that literal appears earlier; change the logic around shell
creation (after parseHtmlForIndexes and applyHeadToHtml where shellParsed,
shellPart and shell are used) to strip the artificial suffix only from the tail
— detect if the resulting string endsWith('</body></html>') and if so remove
that trailing substring (or remove the lastIndexOf occurrence at the string end)
instead of a global/first replace so embedded occurrences are preserved.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 57efd665-b6e7-4b12-9842-cfc632b612a1
📒 Files selected for processing (6)
examples/vite-ssr-vue-streaming/index.htmlexamples/vite-ssr-vue-streaming/src/App.vueexamples/vite-ssr-vue-streaming/tests/streaming.spec.tspackages/unhead/src/stream/server.tspackages/unhead/test/streaming/streaming.test.tstest/exports/vue.yaml
💤 Files with no reviewable changes (1)
- test/exports/vue.yaml
✅ Files skipped from review due to trivial changes (2)
- examples/vite-ssr-vue-streaming/src/App.vue
- packages/unhead/test/streaming/streaming.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- examples/vite-ssr-vue-streaming/tests/streaming.spec.ts
🔗 Linked issue
N/A — surfaced while debugging Vue streaming hydration in
examples/vite-ssr-vue-streaming.❓ Type of change
📚 Description
Vue streaming relied on an SFC AST transform that injected a
<HeadStream />component into every template usinguseHead/useSeoMeta, plus a symmetric client vnode withdata-allow-mismatch— heavy plumbing that also needed a vue-loader patch on webpack/rspack. Replaced it with per-chunk flushing inwrapStream: after each framework stream chunk, any newly added head entries are emitted as<script>window.__unhead__.push(...);document.currentScript.remove()</script>, which executes during HTML parse and removes itself before Vue hydrates. Also splitsprepareStreamingTemplateat the canonical<!--app-html-->/<!--ssr-outlet-->marker so templates can wrap the stream in<div id="app">...</div>without container mismatches.Summary by CodeRabbit
Refactor
Chores