Skip to content

fix(unhead): split streaming template at SSR outlet marker - #750

Merged
harlan-zw merged 2 commits into
fix/streaming-hydration-mismatchfrom
fix/streaming-template-outlet
Apr 22, 2026
Merged

harlan-zw merged 2 commits into
fix/streaming-hydration-mismatchfrom
fix/streaming-template-outlet

Conversation

@harlan-zw

@harlan-zw harlan-zw commented Apr 22, 2026 •

Copy link
Copy Markdown
Collaborator

🔗 Linked issue

Follow-up to #748

❓ Type of change

  • 📖 Documentation
  • 🐞 Bug fix
  • 👌 Enhancement
  • ✨ New feature
  • 🧹 Chore
  • ⚠️ Breaking change

📚 Description

Under a template using the canonical Vite SSR pattern (<div id="app"><!--app-html--></div>), the streaming app output landed before the hydration container instead of inside it, producing a container-level hydration mismatch.

prepareStreamingTemplate now detects <!--app-html--> / <!--ssr-outlet--> and splits the body interior at the marker so the app stream lands inside the outlet's wrapper element.

  • examples/vite-ssr-vue-streaming switches to <div id="app"><!--app-html--></div>; App.vue no longer owns the hydration wrapper.
  • Playwright's hydration-warnings test no longer masks Hydration/mismatch strings so real regressions surface.

Depends on #748 (symmetric HeadStream vnodes) — this branch is stacked on top.

✅ Test plan

  • pnpm -F unhead test
  • pnpm -C examples/vite-ssr-vue-streaming test — existing hydration tests run against the new outlet-based template with the stricter console-warning filter

Summary by CodeRabbit

  • Bug Fixes

    • Improved server-side rendering and hydration handling for Vue applications using streaming.
    • Enhanced outlet marker detection for better template streaming support.
    • Fixed HeadStream component to properly emit during hydration with mismatch tolerance.
  • Tests

    • Updated hydration and streaming regression tests to verify proper DOM marker handling and console error filtering.

`prepareStreamingTemplate` now detects the canonical Vite SSR outlet
(`<!--app-html-->` / `<!--ssr-outlet-->`) and splits the body interior at
the marker so the app stream lands inside the outlet's wrapper element
(e.g. `<div id="app">`) instead of before it. Without this, any template
using the canonical Vite SSR pattern hits a hydration container mismatch.

Example aligned: `examples/vite-ssr-vue-streaming` switches to
`<div id="app"><!--app-html--></div>`; `App.vue` no longer owns the
hydration wrapper. Playwright's hydration-warnings test no longer masks
`Hydration`/`mismatch` strings so real regressions surface.
@coderabbitai

coderabbitai Bot commented Apr 22, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0c3b678f-87f2-49bc-8744-d98b00a5497a

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The changes refactor SSR streaming to use marked outlet locations (<!--app-html-->) for placing streamed content and emit script placeholders with data-allow-mismatch="children" to suppress hydration mismatches during streaming.

Changes

Cohort / File(s) Summary
Example app structure
examples/vite-ssr-vue-streaming/index.html, examples/vite-ssr-vue-streaming/src/App.vue, examples/vite-ssr-vue-streaming/src/entry-client.ts
Reorganized app layout: moved root app div from App.vue to HTML template with SSR outlet marker; removed router readiness guard from client entry point.
Example hydration tests
examples/vite-ssr-vue-streaming/tests/streaming.spec.ts
Added regression test for data-allow-mismatch attributes on streaming scripts; updated console error/warning checks with minimal filtering and post-load delay.
Unhead streaming outlet support
packages/unhead/src/stream/server.ts
Introduced outlet regex detection (<!--app-html--> or <!--ssr-outlet-->); modified template preparation to split and inject streamed content at marked outlet location instead of before closing tags.
Vue HeadStream component
packages/vue/src/stream/client.ts, packages/vue/src/stream/server.ts
Changed HeadStream to always emit <script data-allow-mismatch="children"> placeholder instead of returning null; enables consistent hydration handling during streaming.
Vue plugin documentation
packages/vue/src/stream/vite.ts
Updated JSDoc and comments to describe automatic HeadStream injection and hydration mismatch suppression behavior; removed outdated example code.
Vue streaming component tests
packages/vue/test/streaming.test.ts
Updated assertions to verify HeadStream renders placeholder script with data-allow-mismatch="children"; added scenarios for shell-rendered state and pending entries.

Sequence Diagram

sequenceDiagram
    participant Client as Client (Browser)
    participant Server as Vite SSR Server
    participant Head as HeadStream Component
    participant HTML as HTML Template

    Server->>HTML: Render template with <!--app-html--> outlet marker
    Server->>Head: Render HeadStream component (during shell phase)
    Head-->>Server: Return <script data-allow-mismatch="children"></script>
    Server->>Server: Inject head tags into shell
    Server->>Server: Split template at <!--app-html--> marker
    Server-->>Client: Send shell (before outlet) + placeholder script
    Note over Client: Mount immediately (no router.isReady() guard)
    Server->>Head: Stream head updates (during streaming phase)
    Head-->>Server: Return <script data-allow-mismatch="children" innerHTML="...">
    Server-->>Client: Stream content at outlet location
    Client->>Client: Hydrate with mismatch suppression on marked scripts
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 Streaming now flows through outlets bright,
Scripts with mismatch flags hold tight,
No more null renders clouding the way,
Hydration glides smooth through the fray!
✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: fixing template streaming by detecting and splitting at SSR outlet markers, which is the core technical change across multiple files.
Description check ✅ Passed The description follows the required template, includes a linked issue (follow-up to #748), specifies the type of change (bug fix), and provides clear explanation of the problem, solution, and test plan.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/streaming-template-outlet

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.

@github-actions

Copy link
Copy Markdown
Contributor

Bundle Size Analysis

Bundle Size Gzipped
Client (Minimal) 10.7 kB 4.4 kB
Server (Minimal) 10.6 kB 4.3 kB
Vue Client (Minimal) 11.8 kB 4.9 kB
Vue Server (Minimal) 11.6 kB 4.7 kB

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (3)
packages/unhead/src/stream/server.ts (2)

301-323: Docs: mention the outlet-marker split.

The public JSDoc for prepareStreamingTemplate still only describes splitting at body tag boundaries. Since templates containing <!--app-html--> / <!--ssr-outlet--> now behave materially differently (stream content is relocated into the outlet), it's worth calling this out so users understand when to add the marker.

📝 Suggested doc tweak
 /**
  * `@experimental`
  *
  * Prepares a template for streaming SSR by splitting it at body tag boundaries
  * and injecting head content into both parts.
  *
  * This is the recommended way to handle streaming templates as it:
  * - Uses consistent template parsing (same as transformHtmlTemplateRaw)
  * - Properly injects head content, html/body attrs, and bootstrap script
  * - Injects body tags (scripts at end of body) into the closing part
+ * - If the template contains an outlet marker (`<!--app-html-->` or
+ *   `<!--ssr-outlet-->`) inside `<body>`, the body interior is split at that
+ *   marker so streamed app output lands inside the outlet wrapper (e.g.
+ *   `<div id="app"><!--app-html--></div>`), preventing hydration container
+ *   mismatches.
  *
🤖 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 301 - 323, Update the
JSDoc for prepareStreamingTemplate to explicitly mention that templates are
split not only at body tag boundaries but also at the outlet marker(s) (e.g.,
<!--app-html--> / <!--ssr-outlet-->), and describe the different behavior: when
an outlet marker is present the streamed app content is relocated into that
outlet (instead of the default body insertion), and that html/body attributes,
head injection and bootstrap script handling still apply; reference the function
name prepareStreamingTemplate and the outlet markers <!--app-html--> and
<!--ssr-outlet--> so readers know when to add the marker and what to expect.

356-373: Outlet split logic looks correct.

Placement is right: beforeOutlet (including any wrapper opening like <div id="app">) lands in shell, the stream is written in the gap, and afterOutlet + ssr.bodyTags + endPart puts closing tags (e.g. </div>) before the body scripts and </body></html>. This keeps the hydration root intact and keeps late-injected body scripts in their canonical position.

Two minor notes:

  • OUTLET_RE is a naive substring regex and would also match an <!--app-html--> comment that happens to appear inside an inline <script>/<style> text node. Extremely unlikely in a real index.html, but worth being aware of if templates get more elaborate.
  • Only the first occurrence is used (non-global regex). Silently ignoring a second marker seems fine, but could be worth a dev-mode warning later.
🤖 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 356 - 373, Detect and
handle the two edge cases mentioned: (1) avoid matching an OUTLET_RE inside
inline <script> or <style> by refining the detection in the outlet-splitting
block (use a context-aware check instead of naive substring match — e.g., scan
for the <!--app-html--> comment only in HTML text nodes or ensure it is not
inside a <script> or <style> tag before using outletMatch), and (2) warn in
dev-mode if more than one outlet marker exists (check for additional matches via
matchAll or repeated tests) and log a clear dev warning referencing OUTLET_RE
and the outlet handling logic (the variables outletMatch, beforeOutlet,
bodyInterior, shell) so maintainers are alerted when multiple markers are
silently ignored.
examples/vite-ssr-vue-streaming/tests/streaming.spec.ts (1)

249-268: Broad vite filter may mask real hydration warnings.

The comment explicitly says "No filter for hydration/mismatch", which is the right intent, but !e.includes('vite') is a substring check — a genuine hydration error whose message happens to include a vite-served URL (e.g. a module path) would be dropped. Consider narrowing to known-noisy prefixes (e.g. HMR-related messages) or matching on source rather than text.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@examples/vite-ssr-vue-streaming/tests/streaming.spec.ts` around lines 249 -
268, The current filter in the test 'no unexpected console errors or hydration
warnings' (variables: issues, critical) uses a broad substring check
(!e.includes('vite')) that can mask real hydration warnings; refine the filter
to only ignore known noisy Vite/HMR messages by matching specific HMR patterns
or sources instead of any occurrence of "vite" — for example, inspect the
Playwright console message (from page.on) and match msg.text() or msg.location()
against tighter patterns like HMR endpoints or module-prefixes (/@hmr, /@vite/,
'vite/hmr', or a specific origin) or use a regex that targets only those
prefixes, then update the critical filter to use that narrower check in place of
!e.includes('vite').
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@examples/vite-ssr-vue-streaming/tests/streaming.spec.ts`:
- Around line 249-268: The current filter in the test 'no unexpected console
errors or hydration warnings' (variables: issues, critical) uses a broad
substring check (!e.includes('vite')) that can mask real hydration warnings;
refine the filter to only ignore known noisy Vite/HMR messages by matching
specific HMR patterns or sources instead of any occurrence of "vite" — for
example, inspect the Playwright console message (from page.on) and match
msg.text() or msg.location() against tighter patterns like HMR endpoints or
module-prefixes (/@hmr, /@vite/, 'vite/hmr', or a specific origin) or use a
regex that targets only those prefixes, then update the critical filter to use
that narrower check in place of !e.includes('vite').

In `@packages/unhead/src/stream/server.ts`:
- Around line 301-323: Update the JSDoc for prepareStreamingTemplate to
explicitly mention that templates are split not only at body tag boundaries but
also at the outlet marker(s) (e.g., <!--app-html--> / <!--ssr-outlet-->), and
describe the different behavior: when an outlet marker is present the streamed
app content is relocated into that outlet (instead of the default body
insertion), and that html/body attributes, head injection and bootstrap script
handling still apply; reference the function name prepareStreamingTemplate and
the outlet markers <!--app-html--> and <!--ssr-outlet--> so readers know when to
add the marker and what to expect.
- Around line 356-373: Detect and handle the two edge cases mentioned: (1) avoid
matching an OUTLET_RE inside inline <script> or <style> by refining the
detection in the outlet-splitting block (use a context-aware check instead of
naive substring match — e.g., scan for the <!--app-html--> comment only in HTML
text nodes or ensure it is not inside a <script> or <style> tag before using
outletMatch), and (2) warn in dev-mode if more than one outlet marker exists
(check for additional matches via matchAll or repeated tests) and log a clear
dev warning referencing OUTLET_RE and the outlet handling logic (the variables
outletMatch, beforeOutlet, bodyInterior, shell) so maintainers are alerted when
multiple markers are silently ignored.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: dbb2e1de-54eb-4716-ac7b-2fe344974778

📥 Commits

Reviewing files that changed from the base of the PR and between f717645 and 5b57e76.

📒 Files selected for processing (9)
  • examples/vite-ssr-vue-streaming/index.html
  • examples/vite-ssr-vue-streaming/src/App.vue
  • examples/vite-ssr-vue-streaming/src/entry-client.ts
  • examples/vite-ssr-vue-streaming/tests/streaming.spec.ts
  • packages/unhead/src/stream/server.ts
  • packages/vue/src/stream/client.ts
  • packages/vue/src/stream/server.ts
  • packages/vue/src/stream/vite.ts
  • packages/vue/test/streaming.test.ts
💤 Files with no reviewable changes (1)
  • examples/vite-ssr-vue-streaming/src/entry-client.ts

@harlan-zw
harlan-zw changed the base branch from main to fix/streaming-hydration-mismatch April 22, 2026 15:01
Add `outlet?: RegExp | string | false` to `wrapStream` /
`prepareStreamingTemplate` options. Defaults to the existing
`<!--app-html-->` / `<!--ssr-outlet-->` regex; custom markers or full
opt-out (`outlet: false`) are now supported for users whose templates
use a different placeholder.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant