Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
340c876
Stream Suspense boundaries as marked ranges patched by <preact-island>
MaxwellCohen Nov 22, 2026
51b4714
Stream boundary content as <template for> instead of <preact-island>
MaxwellCohen Nov 22, 2026
39bf960
Let a second copy of the init script leave the first in charge
MaxwellCohen Nov 22, 2026
ce600df
Merge branch 'island-boundary-streaming' into dpu-boundary-streaming
MaxwellCohen Nov 22, 2026
798d6e3
Keep the init script's comments as #12 wrote them
MaxwellCohen Nov 22, 2026
5c08881
Shorten comments
MaxwellCohen Nov 22, 2026
9dc9aa4
Merge remote-tracking branch 'origin/island-boundary-streaming' into …
MaxwellCohen Nov 22, 2026
2036d78
Merge remote-tracking branch 'upstream/main' into island-boundary-str…
MaxwellCohen Nov 28, 2026
7fa3efd
Merge branch 'island-boundary-streaming' into dpu-boundary-streaming
MaxwellCohen Nov 28, 2026
976b537
Use main's useId code from #507 as is
MaxwellCohen Nov 28, 2026
60e248c
Merge branch 'island-boundary-streaming' into dpu-boundary-streaming
MaxwellCohen Nov 28, 2026
5a2c359
Shrink the init script
MaxwellCohen Nov 29, 2026
179f943
Merge branch 'island-boundary-streaming' into dpu-boundary-streaming
MaxwellCohen Nov 29, 2026
ac8f76d
Wrap streamed svg and math content instead of reparsing it
MaxwellCohen Nov 29, 2026
f167bee
Merge branch 'island-boundary-streaming' into dpu-boundary-streaming
MaxwellCohen Nov 29, 2026
66990cb
Hand pending ranges to the client on DOMContentLoaded, drop unmount h…
MaxwellCohen Nov 29, 2026
bbf74e6
Merge branch 'island-boundary-streaming' into dpu-boundary-streaming
MaxwellCohen Nov 29, 2026
26b48d7
Index a chunk's markers once, while still in its island
MaxwellCohen Nov 29, 2026
598ea50
Merge branch 'island-boundary-streaming' into dpu-boundary-streaming
MaxwellCohen Nov 29, 2026
4a32c4d
Use the vnode id for streamed boundaries, like main
MaxwellCohen Nov 29, 2026
810637f
Merge branch 'island-boundary-streaming' into dpu-boundary-streaming
MaxwellCohen Nov 29, 2026
5709d20
Prefix boundary ids per response and write them in base 36
MaxwellCohen Nov 29, 2026
1dcf3bc
Merge branch 'island-boundary-streaming' into dpu-boundary-streaming
MaxwellCohen Nov 29, 2026
95af334
Wait for the island's empty comment, leave cut-off ranges to hydration
MaxwellCohen Nov 29, 2026
dc5e856
Merge branch 'island-boundary-streaming' into dpu-boundary-streaming
MaxwellCohen Nov 29, 2026
cc3bf19
Find a chunk's template by its id
MaxwellCohen Nov 29, 2026
94c185b
Drop the random id prefix, use the vnode id alone
MaxwellCohen Nov 29, 2026
e004fdb
Merge branch 'island-boundary-streaming' into dpu-boundary-streaming
MaxwellCohen Nov 29, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/calm-ranges-stream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'preact-render-to-string': major
---

Mark the range of every `<Suspense>` boundary in the HTML, so the client hydrates each boundary as one unit once all of its content has arrived.

- A boundary that is still to be streamed is written as `<!--$s?id-->fallback<!--/$s?id-->`. Its content follows in `<preact-island hidden data-target="id">…</preact-island>`, the same element as before. The island moves the content into the range once a node follows it (the server writes a newline after each island), then tells hydration the content is there.
- A boundary whose content is in the HTML is written as `<!--$s=-->…<!--/$s-->`, in `renderToString` and `renderToStringAsync` too. One that is left to the client is written as `<!--$s!-->fallback<!--/$s-->`.
- While streaming, the range of a boundary covers all of its children. What a boundary rendered before one of its children suspended is sent with its chunk, and a boundary nested in it is never sent before the HTML that holds its range.

Hydrating these ranges needs the matching Preact release. The markup changes for every `<Suspense>`, so this is a major.
5 changes: 5 additions & 0 deletions .changeset/template-for-stream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'preact-render-to-string': major
---

Stream a boundary's content as `<template for>` (Declarative Partial Updates) instead of `<preact-island>`. Browsers that support it stream the content straight into the page while they parse it, and a small inline script patches it in everywhere else. A pending range now also holds `<?start>`/`<?end>` around its fallback, which mark what the template replaces. Table rows in a chunk keep their structure.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,8 @@ main().catch((error) => {

Preact supports streaming HTML to the client incrementally, flushing `<Suspense>` fallbacks immediately and replacing them with the resolved content as data arrives. This reduces Time to First Byte and allows the browser to start parsing earlier.

The content of a boundary is sent as a `<template for>` ([Declarative Partial Updates](https://github.com/WICG/declarative-partial-updates)). Browsers that support it stream the content straight into the page, and a small inline script does the same everywhere else. A boundary hydrates once all of its content is there, so the client never renders into a boundary the server is still working on.

#### `renderToReadableStream` — Web Streams

```jsx
Expand Down
67 changes: 37 additions & 30 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,22 +37,23 @@ const assign = Object.assign;
const EMPTY_STR = '';
const BEGIN_SUSPENSE_DENOMINATOR = '<!--$s-->';
const END_SUSPENSE_DENOMINATOR = '<!--/$s-->';
// Opens a boundary's range (`$s?id` while it streams, `$s!` for the client)
const BEGIN_BOUNDARY = '<!--$s=-->';

/**
* Wraps a render result with suspense boundary markers, handling all possible
* return types from _renderToString: string, Array, or Promise.
* @param {string | Array | Promise} result
* @returns {string | Array | Promise}
*/
function wrapWithSuspenseMarkers(result, clientOnly = false) {
const start = clientOnly ? '<!--$s!-->' : BEGIN_SUSPENSE_DENOMINATOR;
function wrapWithSuspenseMarkers(result, start = BEGIN_SUSPENSE_DENOMINATOR) {
if (isArray(result)) {
result.unshift(start);
result.push(END_SUSPENSE_DENOMINATOR);
return result;
}
if (result && typeof result.then === 'function') {
return result.then((value) => wrapWithSuspenseMarkers(value, clientOnly));
return result.then((value) => wrapWithSuspenseMarkers(value, start));
}
return start + result + END_SUSPENSE_DENOMINATOR;
}
Expand Down Expand Up @@ -488,6 +489,8 @@ function _renderToString(
);
} catch (err) {
if (isRecoverable(err)) throw err;
// Let the Suspense boundary above stream it
if (renderer && err && typeof err.then == 'function') throw err;
if (type.getDerivedStateFromError) {
component[NEXT_STATE] = type.getDerivedStateFromError(err);
}
Expand Down Expand Up @@ -561,10 +564,13 @@ function _renderToString(
asyncMode
? renderAsyncFallback(renderFallback)
: withSkipEffects(renderFallback),
true
'<!--$s!-->'
);
});

// Suspense classes only, not instances that set `_childDidSuspend` (preact-iso)
const isBoundary = type.prototype && type.prototype[CHILD_DID_SUSPEND];

try {
// Recurse into children before invoking the after-diff hook
const str = _renderToString(
Expand All @@ -584,46 +590,47 @@ function _renderToString(
if (hooks.unmountHook) hooks.unmountHook(vnode);

if (asyncMode && recover && typeof str != 'string') {
return resolveRenderResult(str).catch(recover);
return resolveRenderResult(str).then(
isBoundary
? (html) => BEGIN_BOUNDARY + html + END_SUSPENSE_DENOMINATOR
: undefined,
recover
);
}

if (vnode._suspended) {
return wrapWithSuspenseMarkers(str);
}

// Mark the range the client hydrates as one unit
if (isBoundary) {
return wrapWithSuspenseMarkers(str, BEGIN_BOUNDARY);
}

return str;
} catch (error) {
if (isRecoverable(error)) {
if (!recover) throw error;
if (!renderer || asyncMode) return recover(error);
}
if (!asyncMode && renderer && renderer.onError) {
const onError = (error) => {
return renderer.onError(error, vnode, (child, parent) => {
try {
return withSkipEffects(() =>
_renderToString(
child,
context,
isSvgMode,
selectValue,
parent,
asyncMode,
renderer,
hooks
)
);
} catch (e) {
return onError(e);
}
});
};
let res = onError(error);
// Let the closest boundary render its fallback
if (!isBoundary) throw error;

if (res !== undefined) return res;

if (hooks.catchError) hooks.catchError(error, vnode);
return EMPTY_STR;
return renderer.onError(error, vnode, (child, parent) =>
withSkipEffects(() =>
_renderToString(
child,
context,
isSvgMode,
selectValue,
parent,
asyncMode,
renderer,
hooks
)
)
);
}

if (!asyncMode) throw error;
Expand Down
134 changes: 77 additions & 57 deletions src/lib/chunked.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Fragment } from 'preact';
import { renderToString } from '../index.js';
import { CHILD_DID_SUSPEND, COMPONENT, MASK, PARENT } from './constants.js';
import { COMPONENT, MASK, PARENT } from './constants.js';
import { Deferred } from './util.js';
import {
createInitScript,
Expand Down Expand Up @@ -47,18 +47,16 @@ export async function renderToChunks(
const len = renderer.suspended.length;
if (len > 0) {
// When rendering a full HTML document, the shell ends with </body></html>.
// Inserting the deferred <div hidden> wrapper after </html> is invalid HTML
// and causes browsers to reject the content. Instead, we inject the deferred
// content before the closing tags, then emit them last.
// Inserting the deferred <template for> patches after </html> is invalid
// HTML and causes browsers to reject the content. Instead, we inject the
// deferred content before the closing tags, then emit them last.
const docSuffixIndex = getDocumentClosingTagsIndex(shell);
const initialWrite =
docSuffixIndex !== -1 ? shell.slice(0, docSuffixIndex) : shell;
onWrite(prefix + initialWrite);
onWrite('<div hidden>');
onWrite(createInitScript(nonce));
// We should keep checking all promises
await forkPromises(renderer);
onWrite('</div>');
if (docSuffixIndex !== -1) onWrite(shell.slice(docSuffixIndex));
} else {
onWrite(prefix + shell);
Expand All @@ -76,7 +74,9 @@ export async function renderToChunks(
* @returns {number}
*/
function getDocumentClosingTagsIndex(html) {
return html.lastIndexOf('</body>');
// Ignore a `</body>` inside the content
const match = /<\/body>\s*(?:<\/html>\s*)?$/i.exec(html);
return match ? match.index : -1;
}

async function forkPromises(renderer) {
Expand All @@ -95,39 +95,20 @@ function handleError(error, vnode, renderChild) {
const recoverable = isRecoverable(error);
const suspended = !recoverable && error && error.then;

// Recoverables reach this handler at the boundary itself. Promise retries
// can reach it from a descendant, just like their initial suspension.
if (
!recoverable ||
!vnode[COMPONENT] ||
!vnode[COMPONENT][CHILD_DID_SUSPEND]
) {
while ((vnode = vnode[PARENT])) {
const component = vnode[COMPONENT];
if (component && component[CHILD_DID_SUSPEND]) break;
}
}
if (!vnode) throw error;

const id = vnode.__v;
const found = this.suspended.find((x) => x.id === id);
// Nested boundaries render again with this one's content
abandon(this, vnode);

// An error below a boundary is reported and the boundary is left to the
// client, the same goes for anything that suspends after an abort.
const aborted = this.abortSignal && this.abortSignal.aborted;
if (!suspended || aborted) {
if (!suspended || (this.abortSignal && this.abortSignal.aborted)) {
if (!recoverable && !suspended) this.reportError(error);
abandon(this, vnode);
if (found) {
if (!aborted) this.onWrite(createClientRenderInstruction(id, this.nonce));
return '';
}
return `<!--$s!:${id}-->${renderFallback(vnode, renderChild)}<!--/$s:${id}-->`;
return `<!--$s!-->${renderFallback(vnode, renderChild)}<!--/$s-->`;
}

const completion = new Deferred();
const pending = {
id,
// Unique in the process: the vnode id, short in base 36
id: vnode.__v.toString(36),
vnode,
renderer: this,
renderChild,
Expand All @@ -141,16 +122,15 @@ function handleError(error, vnode, renderChild) {
this.abortSignal.addEventListener('abort', pending.abort);
}

Promise.resolve(error)
.then(retryPending.bind(null, pending), rejectPending.bind(null, pending))
.catch(failPending.bind(null, pending))
.then(
finishPending.bind(null, pending, completion.resolve),
finishPending.bind(null, pending, completion.reject)
);
waitFor(pending, error).then(
finishPending.bind(null, pending, completion.resolve),
finishPending.bind(null, pending, completion.reject)
);

if (found) return '';
return `<!--$s:${id}-->${renderFallback(vnode, renderChild)}<!--/$s:${id}-->`;
// `<?start>`/`<?end>` mark what the chunk's <template for> replaces. The
// closing marker carries the id, so the range is found while nested
// ranges are still streaming in
return `<!--$s?${pending.id}--><?start name="${pending.id}">${renderFallback(vnode, renderChild)}<?end><!--/$s?${pending.id}-->`;
}

/**
Expand All @@ -168,31 +148,66 @@ function renderFallback(boundary, renderChild) {
return renderChild(boundary.props.fallback, parent);
}

/** Retry the boundary once the promise settles */
function waitFor(pending, promise) {
return Promise.resolve(promise)
.then(retryPending.bind(null, pending), rejectPending.bind(null, pending))
.catch(failPending.bind(null, pending));
}

function retryPending(pending) {
const renderer = pending.renderer;
if (!renderer) return;
const vnode = pending.vnode;
const mask = vnode[COMPONENT][MASK];
if (mask) mask[1] = 0;
const suspendedCount = renderer.suspended.length;
const child = pending.renderChild(vnode.props.children, vnode);
const suspendedAgain = renderer.suspended
.slice(suspendedCount)
.some((s) => s.id === pending.id);
if (pending.renderer && !suspendedAgain) {
renderer.onWrite(createSubtree(pending.id, child));
let child;
try {
child = pending.renderChild(vnode.props.children, vnode);
} catch (error) {
// Drop the boundaries found in this attempt
abandon(renderer, vnode, pending);
if (
isRecoverable(error) ||
!error ||
!error.then ||
(renderer.abortSignal && renderer.abortSignal.aborted)
) {
return rejectPending(pending, error);
}
// Suspended again: wait
return waitFor(pending, error);
}
renderer.onWrite(
createSubtree(pending.id, child, renderer.nonce, namespace(vnode))
);
}

/**
* The namespace the parser puts a boundary's content in: `svg`, `math`, or
* empty for HTML (also below an element that switches back to HTML).
* @param {VNode} vnode
* @returns {string}
*/
function namespace(vnode) {
while ((vnode = vnode[PARENT])) {
const type = vnode.type;
if (type == 'svg' || type == 'math') return type;
if (
/^(foreignObject|desc|title|m[inos]|mtext)$/.test(type) ||
// only an HTML annotation switches back to HTML
(type == 'annotation-xml' &&
/^(text\/html|application\/xhtml\+xml)$/i.test(vnode.props.encoding))
)
return '';
}
return '';
}

function rejectPending(pending, error) {
if (!pending.renderer) return;
if (!isRecoverable(error)) throw error;
return handleError.call(
pending.renderer,
error,
pending.vnode,
pending.renderChild
);
clientRender(pending);
}

/**
Expand Down Expand Up @@ -222,12 +237,17 @@ function clientRender(pending) {
renderer.onWrite(createClientRenderInstruction(id, renderer.nonce));
}

/** Complete the pending work at or below a boundary without streaming it. */
function abandon(renderer, vnode) {
/**
* Complete the pending work at or below a boundary without streaming it.
* @param {RendererState} renderer
* @param {VNode} vnode
* @param {Suspended} [except] Work to keep
*/
function abandon(renderer, vnode, except) {
for (const pending of renderer.suspended) {
let parent = pending.vnode;
while (parent && parent !== vnode) parent = parent[PARENT];
if (parent) finishPending(pending, pending.resolve);
if (parent && pending !== except) finishPending(pending, pending.resolve);
}
}

Expand Down
Loading
Loading