Islands and hydration
What the browser does with a page ferrovue rendered.
The server's HTML is complete and readable with no JavaScript. Where the page should be interactive, the client's Vue hydrates the markup: it builds the same components from the same .vue files, finds that the DOM already matches, and attaches to it as it is. That works only if the server wrote exactly the bytes Vue would have written for the same input, which is what ferrovue guarantees; the rest of this page is about giving the client the same input.
There are three ways to hydrate: islands, a page recorded part by part, and a whole app. A page may mix islands with either of the others.
Islands
An island is one component, hydrated on its own from its own props. island() wraps the component's markup in the element the client mounts on, with the props it was rendered from:
// Counter.vue: defineProps<{ start: number }>(), rendering <button>{{ start }}</button>.
let html = counter::island(&counter::Props::new(5)).into_string();
assert_eq!(
html,
r#"<div data-island="Counter" data-props='{"start":5}'><button>5</button></div>"#
);The props travel as JSON, serialised with serde_json into an attribute in single quotes, never in a <script>, so a page under a script-src 'self' policy needs no nonce for them. Only ' can end that attribute and only & can start a reference in it, so those two are the only characters escaped, as ' and &: the JSON's own quotes stay as they are, and the browser gives dataset.props back as the JSON itself. A Float that is NaN or infinite is written as the bare token JavaScript writes (NaN, Infinity, -Infinity) where serde_json alone writes null, so the client gets the number the server rendered; see numbers. An optional prop that is None is left out, which the client reads as undefined, and a nullable one (T | null) is written as null; see props. A Date prop is written as its ISO string, an invalid one as NaN, and the client turns it back into a Date before hydrating; see dates_and_prices. On the client, mountIslands from ferrovue hydrates every island on the page:
import { createPinia } from "pinia";
import { hydrateState, mountIslands } from "ferrovue";
import islands from "ferrovue/islands";
const pinia = createPinia();
hydrateState(pinia); // the state `state_script_into` wrote
await mountIslands(islands, { pinia, router }); // one Pinia and one router for every islandmountIslands and hydrateState read the props and the state back with JSON.parse, taught the three tokens; anything else that is not JSON leaves the island as the server rendered it, and is reported.
ferrovue/islands is written by the Vite plugin (ferrovue/vite): every component that has an island(), keyed by its NAME, each a lazy import(). The bundler gives each island a chunk of its own, and a page fetches only those of the islands it holds. mountIslands also takes components themselves, mountIslands({ Counter }), or a mixture of the two, so a hand-written island can join the others: mountIslands({ ...islands, Chart }). An island whose name is not among them is left as the server rendered it, with a warning naming it (onError handles it otherwise), as is one whose component fails to load.
The islands are exactly the components that have an island(), as the compiler finds while it generates them. That is the only set the server can write data-island for, so it needs no folder convention or list to keep in step: a component becomes an island when the server calls its island(). Each is keyed by its NAME, the file name without .vue, which is what data-island carries.
Islands share the Pinia and router passed to mountIslands, so an island's click handler can change a store another part of the page shows.
Only a component whose render needs nothing but its props has an island(): its data-props is all the client gets. A component that takes slots, the route, stores, translations, teleports, provided values or the page head has html() alone.
Hydrating later
An island hydrates as soon as mountIslands runs, and its code is fetched then. One the reader may never reach, or never touch, can wait: Html::hydrate writes when it hydrates as a data-hydrate attribute on the wrapper, after data-props, and mountIslands loads its component and hydrates it only then.
use ferrovue::html::Hydrate;
let props = reviews::Props { count: 3 };
assert_eq!(
reviews::island(&props).hydrate(Hydrate::Visible).into_string(),
r#"<div data-island="Reviews" data-props='{"count":3}' data-hydrate="visible"><p>3 reviews</p></div>"#
);Hydrate | data-hydrate | The island hydrates |
|---|---|---|
Visible | visible | once any of it is in the viewport (Vue's hydrateOnVisible) |
visible_with("200px") | visible:200px | once any of it is within that root margin of the viewport (Vue's hydrateOnVisible({ rootMargin })) |
Idle | idle | once the browser is idle (Vue's hydrateOnIdle; 200 ms after mounting where the browser has no requestIdleCallback) |
Interaction | interaction | on the first pointerenter, click or focus within it |
InteractionOn(&["keydown"]) | interaction:keydown | on the first of the events named, separated by spaces |
media("(min-width: 60rem)") | media:(min-width: 60rem) | once the media query matches (Vue's hydrateOnMediaQuery) |
The attribute's value is escaped like any other, so a media query or a margin from anywhere is safe to write. A root margin is CSS's, as IntersectionObserver reads it ("200px", "10% 0px"); one the browser rejects is reported through onError and the island hydrates at once. The markup inside the wrapper is what island() writes without it, so hydrating later changes nothing about exactness: the island hydrates against the same bytes, at another moment.
An island waiting for interaction listens on its wrapper in the capture phase, so a focus, which does not bubble, is heard from any element inside it. The events that arrive before it has hydrated (the pointerenter that started the fetch, then the click) are dispatched again on their targets once it has, so the click that woke a button still reaches its handler. Vue's own hydrateOnInteraction replays the first event alone, and has the component's code by then; an island fetches its code first.
mountIslands resolves once the islands that hydrate at once have mounted. The others join apps as they hydrate, and unmount() stops waiting for those that have not. A data-hydrate value the client does not know, from a newer server, is reported through onError and the island hydrates at once.
A waiting island keeps the props it was rendered with, so it hydrates exactly however long it waits. Its handlers do nothing until then, so a control the reader needs at once (a menu toggle, say) is better hydrated at once.
Islands only the server wrote
mountIslands finds islands by their data-island attribute. User HTML that a page renders with v-html keeps that attribute when the sanitiser allows data-* attributes, as DOMPurify does by default, so <div data-island="Link" data-props='{"href":"javascript:…"}'> in a comment would mount the Link island with the props it chose. An IslandKey stops that: render the page inside the key's scope, and every island written there carries the key in data-island-key. Write the key's script, and mountIslands mounts only the islands that carry it, reporting every other to onError:
use ferrovue::html::IslandKey;
let key = IslandKey::random();
let mut page = String::from("<!doctype html><html><body>");
key.scope(|| counter::island(&counter::Props { start: 1 }).render_to(&mut page));
key.script_into(&mut page);
page.push_str("</body></html>");
assert!(page.contains(&format!(r#"data-island-key="{}""#, key.as_str())));
assert!(page.contains(r#"<script type="application/json" id="__fv_island_key">"#));Make a new key for each page with IslandKey::random, which takes 128 bits from the operating system, or give IslandKey::new a key of your own, such as the page's CSP nonce. A key fixed for the whole application is no key: every page shows it, so anyone who reads one can copy it.
The scope covers what is rendered on that thread while it runs, so render each hole's content inside the same key's scope too, when the hole is filled. An island fetched later and mounted with mountIslands({ root }) carries its own response's key: give the fragment its own script, which mountIslands reads from root before the document. The key changes nothing Vue renders: it is an attribute of the wrapper, which the island's app mounts on and does not hydrate. A page without the script mounts every island, as before.
Hydrating a page
A page is often a layout whose slots hold components, each rendered from its own props: a header, a list, a pager, a sidebar. Page records that tree as it is written, so the client can hydrate the layout and everything in it as one app.
Each slot's content is a list of Parts. A part is made from a component's NAME and the Html value that writes its markup, so the props recorded for it are the props it was rendered from. Page::slot takes a slot's parts, Page::hole leaves a slot to be filled while the page streams, and Page::render_to writes the layout and records its props. The record is a <script type="application/json">, escaped as state_script_into escapes the state, so no prop can end the element:
{"props":{"shop":"Ferrovue Books","featured":"Dune"},
"slots":{"default":[{"c":"Pick","p":{"book":{…},"note":"…"}},{"c":"Pick","p":{…}}],
"reviews":[{"c":"Reviews","p":{"reviews":[…]}}]}}A shortened version of the staff picks page in examples/fullstack (src/pages.rs), whose reviews arrive after a slow lookup. The record goes in a hole of its own after the app's container, and PageRecord::script is ready once every hole of the page is filled:
use ferrovue::page::{Page, Part};
let mut page = Page::new();
let parts = page.slot("default", picks.iter().map(|props| Part::new(pick::NAME, pick::html(props))));
let later = page.hole("reviews");
let mut out = String::from("<!doctype html>…<body><div id=\"app\">");
let slots = picks::Slots { default: Some(parts.slot()), reviews: Some(later.slot()) };
let record = page.render_to(&mut out, picks::html(&props, slots, &route));
out.push_str("</div>");
ferrovue::page::hole().render_to(&mut out); // where the record goes
let body = HtmlStream::new(out)
.hole(async move {
let list = catalogue::reviews(&id).await;
later.fill([Part::new(reviews::NAME, reviews::into_html(reviews::Props::new(list)))])
})
.hole(record.script("__fv_page"));A page written at once has no holes, and writes the record with PageRecord::script_into instead.
On the client, mountPage from ferrovue reads the record, loads the components it names and no others, waits for the router, and hydrates the layout on #app:
import { createPinia } from "pinia";
import { hydrateState, mountPage } from "ferrovue";
import islands from "ferrovue/islands";
const pinia = createPinia();
hydrateState(pinia);
const app = await mountPage(() => import("./pages/picks.vue"), islands, { pinia, router });The layout and each component may be given as a component or a loader, as mountIslands takes them, so ferrovue/islands serves when every part has an island(). container and record name another element to mount on and another script to read. The root renders each slot as a plain array of the recorded components, the shape of the markup the server wrote. A v-for over the parts in a template would add a fragment of its own, <!--[-->…<!--]-->, which the server never wrote, and every page would hydrate with a mismatch. mountPage rejects, leaving the page as the server rendered it, when the record or the container is missing or a component is not given or fails to load.
Some things to know:
- A part is rendered from its props. The record holds a part's props and nothing else, so a part takes no slots. It may read the route and the stores, which the app is given.
- An empty slot stays empty. A slot given no parts, or a hole dropped before it was filled, is content to the layout, so its fallback does not show; the client renders it as an empty text node for the same reason.
:slotted()styles are refused. Vue writes the slot scope id of a component with:slotted()styles onto the root of each component in the slot, which a part'shtml()cannot do. A part written into such an outlet panics, naming the id.- An
island()given as a part loses its wrapper. The part belongs to the page's app, so it is written ashtml()writes it, and ahydrategiven to it goes with the wrapper. - A page hydrates at once. The layout and every part are one app, which hydrates as one tree. Vue can defer an async component's hydration inside an app, but it fetches the component's code before the trigger fires, and a part waiting to hydrate would stop following the layout it belongs to. Content that can wait belongs in an island outside the page's container.
Navigating between pages
An application that goes from one server-rendered page to the next without a reload fetches the next document and shows it from its record, with the same app mountPage built for the first page. readPage from ferrovue reads the record and the state's text out of the fetched HTML. It needs no DOMParser, so it also runs in a worker. It finds each script as the HTML parser does, so an id inside a prop, a comment, an attribute or another script's text is passed over. renderPage then renders the record into the page:
import { createPinia } from "pinia";
import { hydrateState, readPage, renderPage, type App } from "ferrovue";
import islands from "ferrovue/islands";
import { linkRoutes } from "ferrovue/link-routes";
import routes from "ferrovue/routes";
let current: App | undefined; // what mountPage returned for the first page
async function navigate(href: string): Promise<void> {
const next = readPage(await (await fetch(href)).text());
const pinia = createPinia();
hydrateState(pinia, { text: next.state });
const links = linkRoutes(routes, { navigate, location: href });
history.pushState(null, "", href);
current = await renderPage(() => import("./pages/picks.vue"), islands, next.record, { pinia, plugins: [links], previous: current });
}renderPage loads the components the record names and no others, builds the app with createPageApp(layout, record, components, { hydrate: false }), which renders the same tree as the hydrated first page, each slot a plain array of its parts, and waits for the router. It then puts an empty copy of the container (#app, or container) in the container's place, mounts the app on it, and unmounts previous after that. The order matters when both pages use one router: vue-router resets a router once the last app using it is unmounted, so the next app is mounted first. It rejects, leaving the page as it is, when the container is missing or a component is not given or fails to load.
Some things to know:
- The links must be at the next page. The browser's location still names the page shown when the next one renders, so links built from it resolve against the wrong route.
linkRoutestakes the next page'slocation, as thehrefitsnavigateis given, and resolves the route there; a router of your own takes a memory history replaced at that location. - The state is the next page's.
hydrateState(pinia, { text })reads the state the fetched page carries,NaNand infinities included, into a fresh Pinia. Settingpinia.state.valueon a Pinia whose stores are already in use leaves those stores on the old state, so either start a new Pinia per page or keep the current one and leave the fetched state aside. - Mount where the URL already names the page. A component that reads
window.locationas it mounts sees the URL of the moment it renders, so push the next URL beforerenderPage. - The record names no layout. The application knows which layout each route uses, as it does for
mountPage. - The head is the app's.
@unhead/vue's client head, given inpluginsto every page, takes the next page's tags as its app mounts and drops the previous page's as it unmounts.
examples/fullstack goes between staff picks this way: client/app.ts gives the page a linkRoutes whose navigate fetches the next page and shows it, pushes the URL, and shows the page the URL names again on popstate.
Islands or a page
Islands hydrate the interactive parts alone: each gets an app of its own, the rest of the page stays static HTML, and the browser fetches only the islands' code. A page hydrates the layout and every part in it: the layout can react to what a part does, every part shares the app's Pinia, router and plugins, and the browser fetches the code of every component the record names.
The record has a cost. It repeats the text of every prop, TrustedHtml bodies included, so where the props are mostly text a page roughly doubles in size before compression. Islands repeat their props in the same way, for the interactive parts alone. ferrovue does not read a TrustedHtml prop back from the server's DOM: the record carries it whole. When size matters, put long prose outside the app's container, where the page writes it once.
Testing a page
hydrateRecordedPage from ferrovue/testing/browser takes a page as the server wrote it (the container and the record's script, or the container and the record as an object), puts it in the document and hydrates it with mountPage. It compares the markup as hydrating leaves it with the markup the server wrote, then waits for the page to settle: a <ClientOnly> shows its content and async components load, which are changes the app makes once mounted. It throws on any change hydrating made, on a node Vue replaced, and on anything Vue warns or logs as an error until the page has settled, and resolves to the app. examples/fullstack runs it on the staff picks page, in happy-dom; its browser test opens the page in Chromium, Firefox and WebKit.
renderRecordedPage takes the same page and shows it again from its record with renderPage, as a navigation shows it, and throws where the client's DOM differs from the markup the browser parsed, and on anything Vue warns or logs as an error. Vue's client and server write some things differently that mean the same, so the two are compared with comments and empty text nodes left out, adjacent text joined, a class by its classes, a style by its declarations (the custom properties Vue's client sets for v-bind() in <style> once mounted, after the others, by name in any order), and an <input>'s value and checked, a <textarea>'s value and an <option>'s selected by the state the browser holds, which the client sets as properties where the server writes attributes. In the markup as parsed, an <option>'s selection is the one the HTML parser gives it from the selected attributes, which happy-dom's property misreports once a later option is selected. The render is compared as mounting leaves it, where a <ClientOnly> still shows the fallback the server wrote, and, where that differs while async components are loading, once they have loaded. What is teleported out of the page is not compared.
With clientRender: true, conformanceSuite holds every fixture to the same comparison: a fresh client render of each shows its recorded HTML. Where Vue's own client render differs from its server render, list the fixture in clientDiffers: a v-model <select> whose value matches no option, an <option> with no value, which the client compares by its text and the server with null, an attribute such as disabled bound on an element without that property, a <TransitionGroup>'s name, the slot scope ids of a slotted component, an async component beside a <ClientOnly>, and the v-bind() variables in <style> the client sets on a root v-for's elements or a <Transition> root, where the server writes none. In Node, where Vue's build sets no such variables, the suite sets them as a browser's Vue does, from what attachSsrRender gives each component.
Preloading the islands
Each island is loaded on demand, and the browser finds its scripts one import at a time: the entry script, once the HTML is parsed; the app and Vue, once the entry runs; the islands, once the page has been read; and what they import. The server knows every island the page holds, so it can name their chunks up front with <link rel="modulepreload">, and the browser fetches them alongside the entry. Chunks reads Vite's manifest (build.manifest: true writes .vite/manifest.json) and .vite/ferrovue-islands.json, which the Vite plugin writes beside it with the chunk that holds each island. An island another component also imports has no chunk of its own, and no key in the manifest: it is bundled into a chunk they share, which that file names.
// Read once, at start-up, from `dist/.vite/manifest.json` and `dist/.vite/ferrovue-islands.json`.
let chunks = ferrovue::page::Chunks::from_manifest(manifest, islands)?;
// For each page:
let mut preloads = chunks.preloads();
let mut head = String::new();
preloads.source_into(&mut head, "client/app.ts"); // a chunk the entry imports dynamically
preloads.islands_into(&mut head, ["Counter"]); // a page's `record.island_names()`, or your own
assert_eq!(
head,
concat!(
r#"<link rel="modulepreload" href="/assets/app.js">"#,
r#"<link rel="modulepreload" href="/assets/vue.js">"#,
r#"<link rel="modulepreload" href="/assets/Counter.js">"#,
)
);An island needs its own chunk and those it imports statically, never the entry, which the page's <script> loads, nor what it imports dynamically. Preloads writes each URL once per page however many islands share it, as most share Vue's chunk; for_islands gives the URLs instead, for a Link header, say. with_base serves them under Vite's base. In development Vite serves the sources and there is no manifest: link nothing.
An island's <style> goes into its chunk too: Linking the stylesheets links it up front.
Preload the islands that hydrate at once. An island given a Hydrate waits to be seen, clicked or idle before it fetches its code; preloading it fetches that code with the page, which is what waiting was meant to spare.
Where the links go:
- Never inside the hydration root. A
<link>in the element an app hydrates is a node the client does not render: a hydration mismatch. Put them in<head>, or in<body>outside the app's container, wheremodulepreloadis allowed too. - A page written at once knows every island before it writes
<head>: render the body first, as the full-stack example does. - A streamed page flushes its head before its content is known. Preload the app and the islands of what is already rendered (the header, the slots given at once) in
<head>, and each hole's islands with its content, after the app's container closes, beside the record's<script>:PageRecord::island_namesnames those of the slots and the holes filled by then, and a hole's parts name themselves withPart::name. Keep onePreloadsfor the page so nothing is linked twice.
Linking the stylesheets
An island's <style> goes into its chunk, and Vite links it only once the island's script has loaded, after the server's markup is on screen, which shows unstyled until then. Link the stylesheets from the page's <head> up front. Chunks reads each chunk's css from the manifest, and Stylesheets writes a <link rel="stylesheet"> for each, once per page:
let chunks = ferrovue::page::Chunks::from_manifest(manifest, islands)?;
let mut stylesheets = chunks.stylesheets();
let mut head = String::new();
stylesheets.entry_into(&mut head, "client/main.ts");
stylesheets.islands_into(&mut head, ["Counter"]); // linked already, through the entry
assert_eq!(
head,
concat!(
r#"<link rel="stylesheet" href="/assets/main.css">"#,
r#"<link rel="stylesheet" href="/assets/Counter.css">"#,
)
);The entry needs its own stylesheets and those of every chunk it imports, statically or dynamically, so linking the entry's covers each island it can load. An island needs those of its own chunk and the chunks it imports statically: link them where a page loads islands the entry does not reach. stylesheets_for_entry and stylesheets_for_islands give the URLs instead, for a Link header. Both follow the manifest's order and with_base. In development Vite injects the styles itself: link nothing. Document links them for the entry and islands it is given. examples/fullstack/src/assets.rs links the entry's, and takes its script's URL from script_for_entry.
The page shell
Document writes the page around a render written at once: the doctype, <html> and <body> with the attributes the Head gives them, the head's tags, a <link rel="stylesheet"> for each stylesheet the entry and the islands need, a modulepreload for each chunk the entry imports and the islands need, and the entry's <script type="module"> at the end of <body>:
use ferrovue::head::Head;
use ferrovue::page::{Chunks, Document};
let chunks = Chunks::from_manifest(manifest, r#"{ "Counter": "assets/Counter.js" }"#)?;
let head = Head::new();
let body = String::from("<main>…</main>"); // the components, rendered first, pushing to `head`
let page = Document::new(head.render())
.with_entry(&chunks, "client/main.ts")
.with_islands(&chunks, ["Counter"]) // the page's `record.island_names()`, or your own
.render(&body);
assert!(page.starts_with("<!DOCTYPE html>\n<html lang=\"en\">"));
assert!(page.contains(concat!(
r#"<link rel="stylesheet" href="/assets/main.css">"#,
r#"<link rel="stylesheet" href="/assets/Counter.css">"#,
"\n",
r#"<link rel="modulepreload" href="/assets/Counter.js">"#,
)));
assert!(page.ends_with("<script type=\"module\" src=\"/assets/main.js\"></script>\n</body>\n</html>\n"));Render the components before the document: the head holds what they pushed only once they have rendered, including what components defineAsyncComponent loads push after the rest, as Vue's server orders it. A streamed page writes its shell itself, as streaming says, since its head goes out before its content is known.
Hydrating the whole app
The other way is the ordinary Vue SSR setup: the server renders the whole page body from one root component (a layout with <RouterView>, say), and the client calls createSSRApp(Root) and mounts it on the same element. Then the client must start from exactly what the server rendered with:
- the same props for the root;
- a router built from the same routes file, with the same base and link classes, and resolved to the current location (
await router.isReady()) before mounting; - Pinia started from the server's state, with
hydrateState; - vue-i18n with the same messages, in the locale the server rendered;
- the same version of Vue that the compiler pinned.
What makes hydration fail
ferrovue's output is the same as Vue's for the same input, so a hydration mismatch means the input differed. The usual causes:
- Different data. The client rendered with different props, state, route or locale.
- Numbers that JSON cannot carry. An
i64beyond ±2⁵³ is rounded by the browser. Anf64that isNaNor infinite travels as a bare token that onlyferrovuereads, so a client that parses the props itself, or aferrovueolder than the crate, cannot read them. Seenumbers. - Markup the browser rewrites. HTML the parser moves or closes, such as a
<div>inside a<p>, does not survive parsing in either renderer; Vue's own SSR has the same constraint. - Comments the client keeps. A client built by Vite's dev server keeps a template's HTML comments, and the server leaves them out unless
ferrovue.config.jsonkeeps them too. See HTML comments. - Content written around a component. A slot closure or a hand-written page part that is not what the client's template would render inside the hydrated root.
One difference hydration does not report: <style scoped> ids that are not the ones the client build chose. The page hydrates cleanly and its scoped styles do not apply; configure scopeId and viteRoot as scoped_styles describes.
The repository's examples/fullstack has tests that render real pages with the server and hydrate them, in happy-dom and in Chromium, Firefox and WebKit, failing on any warning Vue logs, and that check the server's elements carry the scope ids the client build's stylesheet selects; a test like them for the pages of your own app is the way to catch the first cause.