Zova and Next.js: Two SSR Hydration Models, and What Each Gives Up
Next.js has had two generations of SSR paradigms. Zova is isomorphic with the first and heterogeneous with the second. If you lump them together, the comparison loses meaning.
When discussing SSR hydration, the most common question is "What's the difference between Zova and Next.js?"
This question is hard to answer directly, because Next.js itself spans two completely different hydration models:
- Pages Router (the
getServerSidePropsera): server-siderenderToString→ stuff props into__NEXT_DATA__in HTML → client-sidehydrateRoot. This is the isomorphic paradigm of Vue SSR. - App Router (the RSC era): server-side renders React Server Components, outputs Flight protocol payload, and only Client Components participate in hydration. That's a different thing.
Zova belongs to the former, and it goes into more detail than Pages Router. So the really valuable comparisons are two:
- Zova vs Pages Router: within the same paradigm, where are the engineering differences?
- Zova vs App Router: across paradigms, what does each give up?
Let's start with a real request.
1. A single SSR request in Zova
The entry point is in ssrHandler.ts at render(). The whole chain is synchronous and serial:
// 1. Resolve route, determine SSR profile
const route = await this.$$sysRouter.resolveRoute(pagePathFull, true, false);
const ssrProfile = resolveSsrProfile(route.meta.ssrProfile, this.sys.env.SSR_PROFILE);
// 2. Create the app; Controller executes here, data written to ssrContext
renderFn = await serverEntry(ssrContext);
// 3. Synchronously render the whole component tree
const runtimePageContent = await renderToString(renderFn, ssrContext);
// 4. Callback chain: dehydrate query cache, inject meta, dispose request-scoped Context
onRenderedList.forEach(fn => fn(error));
// 5. Assemble the final HTML
const html = renderTemplate(ssrContext);
Three characteristics are worth noting:
First, renderToString is synchronous. Vue 3's official server-side rendering API only has renderToString and renderToSimpleStream; Zova uses the former. That means the server must wait for the entire component tree to finish rendering before it can send the first byte. No Suspense streaming, no progressive transmission.
Second, data isn't "fetched"; it's produced by the Controller. In Zova, page data comes from a backend Controller Bean. During server-side rendering, the Controller executes directly in the backend process (or goes through an internal HTTP call via performAction), and the result is written into ssrContext.state and ssrContext.stateDefer. This is a different data-fetching path from Next.js's await fetch() inside a component.
Third, request-scoped state must be explicitly disposed. Zova's Beans are singletons; request-scoped things hang on ZovaContext. So ssr.ts maintains a SymbolServerContexts set. Each request registers itself, and after rendering it's disposed uniformly:
private _serverContextsDispose() {
for (const serverContext of this[SymbolServerContexts]) {
if (serverContext.disposed) continue;
if (serverContext.bean && serverContext.bean !== serverContext.app?.bean) {
serverContext.bean.dispose();
}
serverContext.dispose();
}
serverContexts.clear();
}
This doesn't exist in Next.js – in App Router, each request is naturally an isolated execution environment; in Pages Router, each request goes through a function once, with no cross-request singleton state to manually clean up.
2. How state gets into the HTML
Zova uses two channels, injecting into different places in the HTML.
In ssrMetaStore.ts:
// Key state → end of head
ctx.endingHeadTags += `<script id="ssr-state-init">window.__INITIAL_STATE__=${unevalPatch(ssrContext.state)}</script>`;
// Non-critical but large state → end of body
ctx.endingBodyTags += `<script id="ssr-state-defer-init">window.__INITIAL_STATE_DEFER__=${unevalPatch(ssrContext.stateDefer)}</script>`;
The two channels hold different things:
| Channel | Location | Content | Characteristics |
|---|---|---|---|
__INITIAL_STATE__ |
end of head | pagePathFull, ssrProfile, ssrProfileOptions, compactHint |
Needed at startup, small |
__INITIAL_STATE_DEFER__ |
end of body | TanStack Query's dehydrate result, Controller load error snapshots, meta |
Large, can be parsed later |
The reason for the split is straightforward: an inline script in the head blocks subsequent parsing. Putting data like the query cache, which can be tens of KB, at the end of the body lets the first screen start sooner.
On the other hand, pagePathFull must be available early – the client needs it to align its route to the server-rendered page, otherwise it would render an empty route first and then navigate, causing a flash.
Client-side restoration is in sys.ssrState.ts:
protected async __init__() {
if (process.env.CLIENT) {
if (cast(window).__INITIAL_STATE__) {
this[SymbolSSRState] = cast(window).__INITIAL_STATE__;
delete cast(window).__INITIAL_STATE__;
document.getElementById('ssr-state-init')?.remove();
}
// stateDefer is similar
}
}
As soon as it's retrieved, it deletes the global variable and removes the script node. Both steps ensure the state is consumed only once and memory is freed.
3. How hydration is detected and closed
Zova doesn't have an explicit call like hydrateRoot. It relies on a DOM signal:
// ssr.ts initialize()
} else if (process.env.CLIENT && document.body.getAttribute('data-server-rendered') !== null) {
this[SymbolIsRuntimeSsrPreHydration].value = true;
}
This data-server-rendered attribute is written into <body> by the server through the default bodyAttrs in _initContext():
ssrContext._meta = defu(ssrContext._meta, {
bodyAttrs: 'data-server-rendered',
// ...
});
So the client knows on startup: "I'm continuing from the SSR DOM" or "I'm mounting from scratch."
Vue 3's createSSRApp().mount() itself goes down the hydrate path, so Zova doesn't need to choose the API manually. But Zova still needs to know when hydration ends – because many pieces of logic (like initializations that can only run once the browser is stable) wait for that moment.
It uses a counter:
public _hydratingRootInc() { if (process.env.CLIENT && this.isRuntimeSsrPreHydration) this._hydratingInc(); }
public _hydratingRootDec() { if (process.env.CLIENT && this.isRuntimeSsrPreHydration) this._hydratingDec(); }
public _hydratingDec() {
if (--this[SymbolHydratingCounter] === 0) {
this._hydrated();
}
}
Root component mount +1, unmount -1, returning to zero means done. _hydrated() does three things:
private _hydrated() {
if (!this.isRuntimeSsrPreHydration) return;
this.isRuntimeSsrPreHydration = false; // flip the flag first
// Give components suspended during hydration a chance to update
this[SymbolInstanceUpdates].forEach(instance => {
if (!instance.isUnmounted && instance.zova) {
try { instance.update(); }
catch (err) { if (!err.message.includes("'insertBefore'")) throw err; }
}
});
this[SymbolOnHydrateds].forEach(fn => fn());
}
That middle "force an update" is key. During hydration, a component's own reactive data may have already changed, but Vue defers rendering to align with the server DOM. After hydration ends, calling update() once brings the page into a truly runtime state. The 'insertBefore' exception is caught because the DOM structure may no longer correspond exactly to the old vnode after hydration; this error is harmless.
On top of that, Zova provides two callback APIs:
onHydrated(fn) // only runs after the first SSR hydration
handleDirectOrOnHydrated(fn) // queues if hydrating, executes immediately otherwise
The second is for general logic. The same code should wait for hydration in SSR scenarios and run immediately in pure SPA scenarios; this wrapper adapts automatically.
By the way, after hydration completes, a marker is set on <html>:
document.documentElement.setAttribute('data-zova-hydrated', this.sys.env.SITE_ID);
It's for external monitoring and end-to-end tests – to determine whether a page truly finished hydration.
4. Compared to Pages Router: the same paradigm
Now put Next.js's Pages Router alongside. Its chain is:
// server
export async function getServerSideProps(ctx) {
return { props: { data: await loadData(ctx) } };
}
// framework generates
<script id="__NEXT_DATA__" type="application/json">{...}</script>
// client
hydrateRoot(document.getElementById('__next'), <App {...pageProps} />);
Compared to Zova, the structure is identical:
| Step | Zova | Next.js Pages Router |
|---|---|---|
| Server rendering | renderToString |
renderToString / renderToPipeableStream |
| State injection | window.__INITIAL_STATE__ + __INITIAL_STATE_DEFER__ |
<script id="__NEXT_DATA__"> |
| Serialization | unevalPatch → JS literal, direct assignment |
JSON, JSON.parse |
| Hydration trigger | <body data-server-rendered> auto-detect |
Framework always calls hydrateRoot |
| Data fetching location | Controller Bean | getServerSideProps |
| Component boundary | None, full tree hydration | None, full tree hydration |
Differences are only in engineering details:
- Zova splits state into two channels; Pages Router has only one
__NEXT_DATA__; - Zova uses a DOM attribute to decide hydration; Pages Router is hardcoded, there's no "should this page hydrate or not" runtime branch;
- Zova has an
onHydratedlifecycle; Pages Router can only fake it withuseEffectinside a component; - Zova's data fetching goes through a Controller, which naturally comes with authentication, permissions, and parameter validation; Pages Router's
getServerSidePropsis a bare function.
So within this paradigm, Zova's position is closer to "patching every weak spot of Pages Router" than to "another way of doing it."
5. Compared to App Router: a different paradigm
App Router's hydration is another story. The key is the 'use client' directive:
// app/page.tsx — default is Server Component, no JS sent
export default async function Page() {
const data = await fetch('https://api.example.com/data');
return <Counter initial={data.count} />;
}
// app/counter.tsx — explicitly declared as Client Component
'use client';
export function Counter({ initial }) {
const [n, setN] = useState(initial);
return <button onClick={() => setN(n + 1)}>{n}</button>;
}
What happens on the server:
- Server Component executes on the server; the
fetchresult stays on the server; - Client Component does not execute; it's serialized into a "placeholder + props + chunk reference";
- Both are compiled into a Flight protocol payload (RSC Payload);
- HTML is generated from the RSC render result; the Client Component's position is an empty container.
After the browser receives it:
- It renders the HTML first (the Client Component position is empty or fallback);
- It loads the RSC Payload, and React runs a
hydrateRooton the root container; - Only at Client Component boundaries does it load the corresponding chunk and mount;
- The Server Component output stays static and never participates in hydration.
Compared to Zova:
| Dimension | Zova | Next.js App Router |
|---|---|---|
| Components needing hydration | All | Only Client Components |
| JS sent | All component code | Only Client Components |
| Data transfer | Custom state object | Flight protocol payload |
| Rendering API | renderToString (sync) |
renderToReadableStream (streaming) |
| First byte timing | After full tree render | Chunked by Suspense boundary |
| Error isolation | One error causes whole page 500 | Fallback within boundary |
| Data fetching | Controller Bean | Direct fetch inside Server Component |
| Hydration mismatch surface | Entire component tree | Only Client Components |
The essential difference in one sentence: App Router cuts off the hydration need at the component source; Zova hydrates the whole tree.
The cost differs too. App Router gets minimal first-screen JS and streaming progressive display at the cost of developers having to understand the Server/Client boundary: useState can only be used in Client Components, Server Components can't have event handlers, cross-boundary values must be serializable, and Server Actions are another mental model.
Zova gets "a single component that runs on both ends"; any SFC can directly write ref, onMounted, $useState without thinking about boundaries. The cost is that the first-screen JS includes all component code, and the whole tree bears mismatch risk.
6. Three Zova-specific details
6.1 Two-channel state, to start the first screen earlier
This was mentioned above; here's a design judgment. __INITIAL_STATE__ holds only the fields needed at startup; the query cache goes through the defer channel. This split has no equivalent in Pages Router – Next.js stuffs all props into one __NEXT_DATA__, and large pages' initial state slows down head parsing.
Zova's approach is essentially a manual prioritization between "critical rendering path" and "non-critical data."
6.2 Controller load errors are "replayed"
This is Zova's most interesting part. In ssr.ts, controllerLoad:
public controllerLoad(event: IControllerLoadEvent) {
if (event.phase === 'prepare') {
if (process.env.SERVER) {
event.ctx.meta.state.controllerLoadKey = this._allocateControllerLoadKey(event);
return;
}
// Client hydration phase
const key = this._allocateControllerLoadKey(event);
const snapshot = this.stateDefer.controllerLoad?.[key];
if (!snapshot || snapshot.controllerBeanName !== event.controllerBeanName) return;
delete this.stateDefer.controllerLoad![key];
event.replayError = _createControllerLoadError(snapshot);
event.replayControllerRecorded = snapshot.controllerRecorded;
return;
}
// Server: store the error as a snapshot
if (event.phase !== 'fallback' || !process.env.SERVER || !event.error) return;
const key = event.ctx.meta.state.controllerLoadKey;
if (!key) return;
(this.stateDefer.controllerLoad ??= {})[key] = _createControllerLoadErrorSnapshot(event);
}
The flow:
- Server-side Controller load fails (e.g., 401, 404, redirect);
- Serialize the error's
name / message / code / status / pagePathinto a snapshot, store it instateDefer.controllerLoad; - On the client, when hydration reaches the same Controller, use the same structural key to find the snapshot;
- Directly "replay" the error, instead of making a new request.
Why replay? Because the client and server may have different auth states, cookie availability, and request contexts. If the client re-fetches, it could get a different result – the server redirects to login, but the client gets data, and hydration breaks. Replay guarantees that both ends get identical load results for the same Controller.
The key generation is worth a look: it concatenates the component path from root to current, vnode key, and occurrence order within the same name:
const parts: string[] = [];
let current: ComponentInternalInstance | null = instance;
while (current) {
const name = current.type.__file ?? current.type.name ?? current.type.__name ?? 'anonymous';
parts.unshift(`${name}:${String(current.vnode.key ?? '')}`);
current = current.parent;
}
const structuralKey = parts.join('/');
const occurrence = this._controllerLoadSequence[structuralKey] ?? 0;
this._controllerLoadSequence[structuralKey] = occurrence + 1;
return `${structuralKey}#${occurrence}:${event.controllerBeanName ?? ''}`;
This distinguishes cases where "the same Controller appears multiple times in a page" – each instance gets its own error.
Next.js has no equivalent. In App Router, a failed fetch is encoded into the RSC Payload and caught by an error boundary; in Pages Router, a getServerSideProps error just returns 500. Neither has a need to "replay the same failure across ends," because their data fetching only happens on the server.
6.3 Attribute mismatches are tolerated
Vue's hydration by default errors on attribute differences. Zova adds a default lenient policy:
private _onHydratePropHasMismatchDefault(el, key, clientValue, _vnode, _instance) {
let ignore = false;
if (key === 'class') {
ignore = true;
if (clientValue !== undefined) {
el.setAttribute('class', normalizeClass(clientValue));
}
} else if (key === 'style') {
// similarly, overwrite with client value
} else if (['id', 'name', 'for', 'd', 'aria-labelledby', 'aria-controls'].includes(key)) {
// overwrite directly
} else if (key === 'value') {
// textarea uses .value, others use setAttribute
} else if (isBooleanAttr(key)) {
// boolean attributes are handled by presence/absence
} else if (el.getAttribute(`data-hydrate-ignore-${key}`) !== null) {
// developer manually marked to ignore
}
return ignore ? { ignore: true } : { clientValue };
}
The set of overwritten attributes is deliberate:
class/style: server and client may compute different results due to animations, themes, or responsive breakpoints; that shouldn't count as an error;id/name/for/d/aria-*: these often appear in auto-generated IDs, SVG paths, and accessible relationships; slight differences don't affect functionality;value: input values may have been changed by the user; hydration shouldn't overwrite them with server values;- boolean attributes:
disabled,checked, etc., are handled with "presence/absence" semantics, which is more stable.
There's also a manual escape hatch: data-hydrate-ignore-${key}. Add data-hydrate-ignore-title to an element, and that attribute won't error during hydration; the client value is used directly.
The value of this policy is that it separates "reasonable differences" from "real bugs." It defaults to letting the former pass, so developers can notice the latter.
7. Resource preloading: the difference isn't the manifest, it's "when you know what's used"
Two things must be separated, otherwise you'll draw wrong conclusions:
- The mapping table from modules to output files, i.e.
quasar.manifest.json. It's a build artifact – production builds generate it, development builds generate it too, and it's read-only during requests and never changes. - Which modules this request actually uses. This is runtime information; you only know after running the entire component tree.
Zova's approach: first use item 2 to filter the set, then use item 1 to look up the table:
// ssrHandler.ts
const modules = cast(ssrContext).modules;
if (modules) {
ssrContext._meta.endingHeadTags += this._renderModulesPreload_zova(modules, { ssrContext });
ssrContext._meta.endingHeadTags += this._renderModulesPreload(modules, { ssrContext });
}
And the collection of item 2 is production-only. In a-ssr/src/monkey.ts, moduleLoaded says:
async moduleLoaded(module: IModule) {
// ssrContext.modules
if (process.env.SERVER && process.env.PROD) {
if (!this.ctx.meta.$ssr.context.modules) this.ctx.meta.$ssr.context.modules = new Set();
this.ctx.meta.$ssr.context.modules.add(`@@${module.info.relativeName}`);
}
}
So in development, Zova module modulepreload tags aren't generated at all, not "generated after rendering."
The manifest's structure also confirms it's a build artifact: keys are source module paths or hashed output filenames; values are those files' dependency lists. For example:
{
".quasar/prod-ssr/client-entry.js": ["/assets/index-xxxx.js"],
"a-api-DvAtaMhL.js": ["/assets/wrapAsyncGenerator-DhsawSOn.js"]
}
Zova takes @@a-api and reverse-looks-up a key that starts with a-api- and ends with .js. On a hit, it caches the result in _ssrModulesZovaCache – a process-level, never-invalidated cache:
const prefix = `${id.substring(2)}-`;
const postfix = '.js';
for (const key in this._clientManifest) {
if (key.startsWith(prefix) && key.endsWith(postfix)) {
cache = this._resolveUrlPath(`/assets/${key}`);
break;
}
}
Note this does "iterate the manifest for a prefix match", because the manifest goes "file → dependencies", not "module → file", so a reverse lookup is needed. After a match, the tag type is dispatched by extension: js goes to modulepreload, css to stylesheet, fonts and images to preload.
So the real difference isn't in when the manifest is generated – both are build-time. The difference is:
Can "which chunks this page needs" be statically determined before rendering?
App Router can. The mapping between route segments and chunks is static in the build output; the server knows what to preload before rendering. Combined with chunk references embedded in the RSC Payload, the browser can even prefetch when a user hovers over a <Link>.
Zova cannot. Because Zova's modules are loaded at runtime on demand – only when routing reaches a point does app.meta.module.use(relativeName) load that module. So "which modules this page hits" depends on the Controller's loading path and the actual expansion of the component tree; you only know after rendering finishes.
In other words: the mapping is static, the hit is dynamic. A pre-built static mapping isn't enough to move preloading earlier; what really determines timing is "can the page-chunk binding be solved before rendering."
Pages Router sits in between – it has a build artifact, but preloading mostly relies on next/link and <Head>, not as deeply integrated as App Router.
8. Trade-offs
Put both sides in one table to see what each gives up:
| Zova | Next.js Pages Router | Next.js App Router | |
|---|---|---|---|
| Component mentality | One component runs on both ends | Same | Must distinguish Server / Client |
| First-screen JS | Whole component tree | Whole component tree | Only Client Components |
| TTFB | After full tree render | Can stream | Streaming + chunking |
| State injection | Two channels | One channel | Flight Payload |
| Data fetching | Controller Bean (full backend capability) | getServerSideProps (bare function) |
Component fetch (with cache semantics) |
| Hydration lifecycle | onHydrated / handleDirectOrOnHydrated |
None, use useEffect |
None, use useEffect |
| Pre-hydration state consistency | Error snapshot replay | Not guaranteed | Guaranteed by RSC Payload |
| Cache granularity | public / session two levels | Page-level | Route segment + fetch + tag |
| Migration cost | — | Low (isomorphic) | High (paradigm switch) |
Three judgments:
Zova chooses "full application runs on both ends", keeping all complexity inside the framework (two channels, error replay, attribute tolerance, Context lifecycle), hidden from the developer. This is a choice of "the framework does a bit more, the developer thinks a bit less."
Pages Router is a different implementation of the same choice, but with less polish on details. Its historical value lies in proving that "HTML-embedded initial state + hydrateRoot" is a road that works for many years.
App Router is a paradigm switch. It acknowledges the cost of "full hydration" and uses component boundaries to gain first-screen performance. The price is pushing complexity onto developers – every component must be considered: "where does this code run?"
So the question "which hydration is better, Zova or Next.js?" has no unified answer; it depends on whether you'd rather put complexity in the framework or in your head.
9. Summary
- Next.js has two generations of SSR paradigms: Pages Router is isomorphic with Zova (HTML-embedded state + full-tree hydration); App Router is heterogeneous (RSC + selective hydration). Comparisons must first distinguish this layer.
- Zova's server-side chain is
resolveRoute → serverEntry → renderToString → onRendered → renderTemplate, synchronous and serial, with no streaming chunks. - State goes through two channels:
__INITIAL_STATE__into head (startup-required),__INITIAL_STATE_DEFER__into body (large, deferrable). - Hydration is detected via
data-server-rendered, closed by aHydratingCounterreaching zero, and at that point instances suspended during hydration get a forcedupdate(). - Three Zova-specific details are worth borrowing: two-channel state prioritization, cross-end replay of Controller load errors, and categorical tolerance of attribute mismatches.
- If Zova were to evolve further, the two things worth borrowing from App Router are streaming rendering and component-level JS trimming; but both require reworking the backend response pipeline and the component model, not small changes.
References and Source Code
Zova / Cabloy
- SSR context and hydration lifecycle
- SSR state restoration
- State injection and meta management
- SSR rendering service
- Query cache dehydrate / hydrate
- Route alignment between server and client
- SSR module assembly and hydrated hooks