renderToString
Renders a JSX tree into an HTML string.
Signature#
declare function renderToString(node: unknown): Promise<string>;
node is a single JSX node: a component, an element, a fragment (<></> for
several siblings), or any Renderable. It is
typed unknown because JSX's own typing already constrains what compiles.
Usage#
import { renderToString } from "@vincle/core";
const Page = ({ title }: { title: string }) => (
<html>
<head>
<title>{title}</title>
</head>
<body>
<h1>{title}</h1>
</body>
</html>
);
const html = await renderToString(<Page title="My Site" />);
Async components#
Any component in the tree can be async: the component that needs data fetches
it, and the returned promise resolves once the whole tree has rendered.
import { renderToString } from "@vincle/core";
declare const db: {
posts: {
findAll(opts: { limit: number }): Promise<{ id: number; slug: string; title: string }[]>;
};
};
const Feed = async () => {
const posts = await db.posts.findAll({ limit: 10 });
return (
<ul>
{posts.map((p) => (
<li key={p.id}>
<a href={"/posts/" + p.slug}>{p.title}</a>
</li>
))}
</ul>
);
};
const html = await renderToString(<Feed />);
Siblings start in document order and overlap as soon as one of them awaits:
their synchronous prefixes always run in document order, then their async work
proceeds concurrently, in arrays, iterables and precompiled templates alike.
The output is joined in document order, whatever the completion order. Scope
is shared by the whole render and never arbitrated: a Scope.set before a
component's first await is visible to later siblings; one placed after an
await races with the other siblings, so which reader sees it depends on
timing. When a sibling throws or rejects, renderToString rejects at once
with that failure: siblings already in flight are not awaited or cancelled -
their work finishes in the background and a late failure is swallowed.
Concurrent renders#
Concurrent calls are safe, even when components use Providers or Scope.with:
each render keeps its own values, with no cross-request leakage.
const [pageA, pageB] = await Promise.all([renderToString(<PageA />), renderToString(<PageB />)]);