JS runtime
How zfb hosts JavaScript execution server-side via an embedded V8 isolate, and why the runtime is fixed by the binary.
This page is the implementation-detail reference for zfb's current backends — the bundler and JSX transform, the V8 host — and how they got here. For the reader-level model, start with How zfb works.
Today: on the build machine, zfb build and zfb dev run your server-side JavaScript in V8, embedded in the zfb binary through zfb's own Rust host layer (the "direct V8 host" in the zfb-js-host crate). V8 is the engine; the direct host is only the layer between zfb and V8. In production, request-time pages run in Cloudflare's workerd, and browser code runs in the visitor's browser engine. Rendering in all of these is done by zudo-react, zfb's own component model. The details are in What runs today and Current defaults and experiments; the sections between them that describe the evaluation are history.
How the runtime choice was reached
Historical context
This section and Why a JS engine at all record how the engine was chosen. Some of that evaluation predates zudo-react and used Preact components as test cases; it does not describe the current rendering model.
The V8 embedding decision came through a measured evaluation of available JS hosts. In order:
Early iterations embedded V8 in-process through
deno_core, chosen after spiking three candidates:deno_core,ssr_rs, andrquickjs.zfb then moved to a Node-hosted miniflare worker to get runtime parity with the Cloudflare Workers production target.
Tauri distribution reversed that: shipping zfb as a desktop app requires a single binary with no Node.js dependency on end-user machines, and miniflare is a Node package. Embedding V8 through
deno_corewas therefore adopted again — accepting the binary-size and first-build-time costs — because it was the only path that satisfied the no-Node single-binary constraint. Released binaries up to v4.6.0 use this host.Later, zfb replaced
deno_corewith its own host that drives thev8crate directly: #4390 made it the default, and #4395 removed thedeno_corehost.
V8 has been the embedded engine since step 3; only the layer between zfb and V8 changed in step 4.
The stable production contract throughout has been the bundle shape (export default { fetch }), not the build-time engine. The build-time bundle and the bundle deployed to Cloudflare Workers for runtime SSR share that shape, but they are not the same bytes: with an adapter configured, zfb runs a second bundle pass limited to the prerender = false routes, and that bundle is what deploys (see The fetch contract across hosts).
Why a JS engine at all — and why V8 specifically
zfb uses a JS engine not because TSX requires one, but because evaluating the compiled output does. The distinction matters.
Layer 1 — JSX is just syntax
SWC, oxc, and esbuild all compile JSX to h(...) calls — none of them need a JS engine to do it. Parsing and transforming TSX is a pure syntax operation. So "we support TSX" does not logically imply "we need V8." The question is what happens after the transform.
Layer 2 — The compiled JS still needs to run
Once JSX becomes h(...), something must evaluate that code and turn the result into HTML. (At the time of this evaluation that meant building a Preact VDOM and calling renderToString; today zudo-react runs each component once and renders its description directly, with no tree reconciliation — see the zudo-react overview.) Evaluation needs a JS engine somewhere — but not necessarily V8. Two lightweight alternatives exist:
Boa (pure Rust, ~30 s incremental build) — a JS engine written entirely in Rust with no C++ toolchain; tracks the ECMA spec but trails V8 on coverage of newer features.
rquickjs (Rust bindings to QuickJS, ~210 KB binary contribution) — fast to compile, minimal footprint.
During the original JS-host evaluation, both worked well for SSR of the simple, self-contained Preact component used as a test case. The broader problem was "any frontend dev's TSX with whatever npm packages they imported." When a user added a calendar library, an i18n helper, or a component that used a Proxy-based state store, Boa's ECMA gaps and QuickJS's limited ES2022+ surface could produce silent wrong output or hard panics — failure modes that were extremely hard to diagnose. V8 was the safe bet for arbitrary ecosystem code because it is the same engine Node.js and Chromium run against.
Research is open on both lighter-engine paths — see #344 — feature-gated V8 in the production runtime and #345 — Boa / QuickJS as the SSG-only JS engine.
Layer 3 — Rust templating compiles out the JS entirely
Leptos and Yew take JSX-like syntax (RSX) and compile it to Rust at build time. No JS engine is needed at runtime or build time. The catch: they borrowed the syntax, not the language. There is no import for arbitrary npm packages and no JS closures over runtime values. A Leptos project is a Rust project — you write Rust, you depend on Rust crates. That breaks the core audience promise: a frontend developer's existing TSX and npm knowledge would not transfer.
The audience tradeoff
zfb's target audience is frontend developers who already know TSX and npm. V8 is the price of admission for that audience: it gives the compiled page and the npm code it imports full, standard JavaScript semantics, so language-level behavior does not silently differ from what the same code does in Node.js or a browser. That is a statement about the language, not about APIs or component libraries. V8 does not make Node.js APIs available (see host APIs), and it does not make React or Preact components work — zfb renders zudo-react, which is its own component model. The design philosophy section explains this audience-first framing in full.
Pure-Rust SSG (Boa/QuickJS) and no-V8-at-runtime (build-time-only V8) are real future directions — see #344 and #345 — but they are optimizations on top of the default, not the default itself.
What runs today
At zfb build / zfb dev, the Rust orchestrator creates an in-process V8 isolate through the direct V8 host in the zfb-js-host crate. It loads the workerd-shape bundle that the bundler builds around createPageRouter from @takazudo/ (the native Rolldown bundler; see Current defaults and experiments). Per-route props are passed as JSON; the isolate invokes the bundle's fetch entry with a synthetic Request, collects the Response (HTML), and returns it. The orchestrator writes plain HTML to dist/. No subprocess is spawned; no Node.js is required.
V8 itself is initialized once per process, on the main thread, before the CLI starts Tokio or any host thread (zfb-js-host::process::initialize). Only one host may be alive on a thread at a time.
For runtime SSR of prerender = false routes, a bundle of the same export default { fetch } shape deploys to Cloudflare Workers, where workerd executes it on request. It is the adapter's narrowed second bundle, not the bytes the embedded host rendered at build time. The production path is unaware of which build-time engine produced the bundle.
Transformation, engine, host APIs and rendering
"zfb runs my TSX" covers four responsibilities that are worth keeping apart:
| Responsibility | What it is | Where it happens in zfb |
|---|---|---|
| Transformation | Parsing TSX/JSX/MDX and bundling it into JavaScript modules. A pure syntax operation; no engine is involved. | The native Rolldown bundler embedded in the zfb CLI, using zudo-react's automatic JSX runtime (@takazudo/). SWC is used for some source analysis. |
| JavaScript engine | The thing that executes the transformed JavaScript. | V8 everywhere: the CLI's embedded V8 on the build machine, the V8 inside workerd on a Worker, and the browser's engine in the browser. zfb's direct V8 host is a host around V8, not a different engine. |
| Host APIs | The globals and built-in modules the host chooses to expose. | The embedded host implements module loading and the Web request/response services the page router needs. Its node:fs, node:fs/promises, node:path, node:url, node:buffer and node:async_hooks modules are stubs that throw node:* is not available under the SSG runtime when used (crates/). On a Worker, Cloudflare's runtime decides, and the adapter requires nodejs_compat for node:async_hooks. The browser provides the DOM. |
| UI rendering | Turning components into HTML strings and live DOM. | zudo-react: renderToString from @takazudo/ in the page router; hydrate/mount from @takazudo/ in the browser. |
Each layer constrains a different thing. Language support is the engine's job; which APIs exist is the host's; which component model works is the renderer's. So "V8 runs it" does not imply "Node.js APIs are available", and neither implies "React components render".
The fetch contract across hosts
The bundle shape — export default { fetch } — is the contract a Cloudflare Workers deployment expects, and it is also what the embedded host drives at build time. The routing core (createPageRouter from @takazudo/) is built on Hono, a small Web-standard router library, and follows its adapter pattern: one router, multiple entry adapters. The build-time host feeds it synthetic Request objects and collects Response bodies; the Cloudflare adapter registers it as the Worker's fetch handler through _worker.js. The router does not know which host is driving it.
Fixing the shape as the stable contract keeps zfb decoupled from which JS engine host executes it: the build-time host is the embedded V8 isolate, the production host is workerd. What is shared is the shape, not the bytes. When the project sets adapter: "@takazudo/zfb-adapter-cloudflare", zfb build runs a second bundle pass whose entry imports only the prerender = false routes (and drops content-collection imports and the content snapshot), and the adapter wraps that bundle. See SSR on a Worker for the emitted files.
The layering this contract allows:
| Layer | What it owns | What it does NOT own |
|---|---|---|
| Your source | Pages, components, content, styles | Build mechanics |
| zfb | The build contract — route table, page props shape, island protocol, client-script pipeline, dist/ layout | Which bundler, which JS host |
| Tools | The bundler (Rolldown), the embedded V8 host (build-time evaluation) | Your code's semantics |
The bundler and the embedded V8 host are implementation details that can be swapped without touching user code: the bundler behind the zfb-bundler crate's typed bundle request, the host behind the RenderHost trait (The boundary).
The need
zfb's renderer compiles a page's TSX through SWC, hands the resulting ESM to a JS host, calls the module's default export, and writes the returned HTML to disk. The host must:
support ESM (
import/export) so pages can import shared components naturally,support top-level
awaitso a page canawait fetch(...)orawait loadCollection(...)at module scope,surface thrown errors with source-accurate locations — the stack-trace line must match the line in the user's TSX file, not an offset into a wrapped script,
evaluate the same module repeatedly across a build of hundreds of pages without leaking memory.
Runtime candidate evaluation
A now-removed spike crate implemented the same RenderHost trait against three candidates, gated behind cargo features so the heavy V8 build was opt-in. The following table is historical context — this evaluation informed the runtime choice.
Candidates
deno_core— V8 wrapped by Deno's reusable core. Ships an ES module loader, an event loop for top-level await, and source-mapped errors out of the box. Chosen by this spike, and used until #4395 replaced it with the direct V8 host.ssr_rs— a thin V8 wrapper specialised for Preact / React SSR. Narrower scope, single-bundle entry-point model.rquickjs— Rust bindings around QuickJS. Small footprint, fast to compile, single-threaded.
Two more were rejected without a measured spike. rusty_v8 is the same V8 we would get through deno_core, only at a lower level — choosing it means re-implementing the loader and isolate plumbing deno_core already gives us. (That cost was later accepted on purpose for the direct V8 host described below, which talks to the v8 crate directly and is now zfb's only runtime.) boa is a pure-Rust ESM implementation; ECMA conformance and source-map fidelity trail V8 by enough that real-world Preact / React SSR hits unsupported corners.
Trade-off matrix
The spike's bench harness loaded five representative scenarios — static page, dynamic route, content collection, "use client", and top-level await — and measured cold start, warm mean, warm p95, and steady-state RSS. Headline numbers from the measurement run:
| Axis | deno_core | ssr_rs | rquickjs |
|---|---|---|---|
| Warm render | 16us | 1.37ms | 106us |
| Cold start | 181us | 5.88ms | 572us |
| Steady-state RSS | 19MB | 317MB | 4.5MB |
| ESM | native | bundle | partial |
| Top-level await | native | bundle | not supported sync |
| Source maps | native | partial | offsets only |
| Build cost | ~3 minutes | similar | ~30 seconds |
The V8-class engines win on the correctness axes; QuickJS wins on footprint and build cost. ssr_rs's default per-render isolate creation dominates everything else and accumulates memory under load.
This build-cost row is not the workspace build time
The ~3 minute figure above is the now-removed spike crate compiling its deno_core dependency in isolation — one crate, one dependency graph. It is not the same measurement as the 15–30 minute cold first cargo build of zfb's whole workspace described in Why Rust, which compiles every workspace crate plus V8 together. The two numbers describe different build scopes.
Constraints zfb imposes
Two project-level invariants shape the choice.
Single isolate per render thread. V8's isolate is pinned to one thread. The renderer treats the host as !Send and runs it on a dedicated thread, exchanging work over a channel. A per-thread guard refuses a second live host on the same thread, and config evaluation creates a fresh host for each call.
The runtime is fixed by the binary, not by config. zfb.config.ts cannot pick its own JS runtime, and there is no CLI flag for it either. The runtime is whatever the zfb binary you installed was compiled with, chosen by Cargo features at build time. That keeps the contract between zfb and user code single-valued — every project built with one binary uses the same runtime. The bootstrap rule lives in crates/.
The boundary
Everything above the host is written against the RenderHost trait in crates/:
#[async_trait(?Send)]
pub trait RenderHost {
async fn execute_module(&mut self, name: &str, source: &str) -> Result<ModuleHandle>;
async fn call_default(&mut self, handle: &ModuleHandle, props: JsonValue) -> Result<String>;
async fn get_export(&mut self, handle: &ModuleHandle, name: &str) -> Result<JsonValue>;
}That is the entire surface the renderer uses. zfb-render, zfb-build, and the framework adapters never name the concrete runtime. The implementation can be swapped without touching call sites — add a new host, re-run the bench, and run the adapter integration tests to confirm byte-identical HTML.
zfb-render exports the direct V8 host, zfb_js_host::native::NativeHost, under the name EmbeddedV8RenderHost, so zfb-build, the dev server and the CLI's thread adapter use that name and never refer to the host crate directly.
Current defaults and experiments
zfb has one JS runtime: the direct V8 host in the zfb-js-host crate. It drives the pinned v8 crate (=147.4.0) directly and implements module loading, the Web API services, dispatch and dev reload itself. It is the default direct-v8 Cargo feature since #4390. #4395 removed the former deno_core-backed host, its embed_v8 feature, and the deno_core, deno_ops, deno_error and serde_v8 crates. Released binaries up to v4.6.0 still use the deno_core host; releases cut after #4395 use the direct host.
Cargo features choose the build when zfb is compiled from source:
# Default: the direct V8 host
cargo build --locked -p zfb --bin zfb
# Slim: no V8
cargo build --locked -p zfb --no-default-features --bin zfbThe ICU 77 data that V8 needs is vendored at
crates/and embedded at compile time. No environment variable or download is needed.zfb- js- host/ icu/ icudtl. dat The slim build has no V8. It evaluates
zfb.config.tsthrough anodesubprocess (so it needsnodeonPATH), andzfb buildandzfb devstop with an error that namesdirect-v8 = off.
Known limitations of the direct host:
Interrupting CPU-bound JavaScript, such as a page stuck in an endless loop, is not supported. The host sets no CPU-time limit and no hard heap limit. When the CLI's threaded host adapter shuts down, it waits up to 10 seconds for its V8 thread and then detaches it; a detached thread is not a clean isolate shutdown.
The qualification harness's watchdog drains a killed child's output on a best-effort basis (#4289). This limits the evidence harness, not the shipped CLI.
A label-triggered, non-required CI lane (direct-v8.yml) records native rows on Linux x64, Linux arm64 and Windows x64. Darwin rows are run by hand on a Mac. The contributor-side details are in prototypes/.
The native Rolldown compiler bundles pages, islands, client scripts, plugins and zfb.config.ts; zfb no longer ships or runs esbuild. Setting ZFB_BUNDLER or ZFB_ROLLDOWN_PROTOTYPE to any value is an error.
zfb preview does not rebuild: it serves built output, or delegates to Wrangler with the Cloudflare adapter. It does not generally render pages through the embedded V8 host.