NextCompile (Cloudflare Runtime)
readyNextDeploy's pure-Go compiler and NextServer Worker engine that runs unmodified Next.js 14/15/16 + Turbopack apps directly inside Cloudflare Workers (workerd) — with a build-time Virtual FS, static chunk registry, zero-buffering streaming HTTP bridge, and R2 + KV CacheHandler.
Source reference: shared/nextcompile/, shared/nextcompile/runtime_src/nextserver/, cli/internal/serverless/cloudflare/adapter/
Why NextCompile Runs NextNodeServer Inside workerd
Cloudflare Workers execute inside V8 isolates (workerd) rather than a Linux container — they cannot spawn a child node process or read from a local disk.
Early Cloudflare adapters tried to solve this by reimplementing Next.js's router, RSC Flight serializer, metadata merger, middleware executor, and Server Action dispatcher from scratch. Every Next.js release — especially Next.js 16's default Turbopack bundler — breaks custom reimplementations.
NextCompile solves this with two engines controlled by serverless.cloudflare.engine:
| Engine | When Used | How It Works |
|---|---|---|
nextserver | Default for Turbopack & Next.js 16+ (engine: auto), or explicit engine: nextserver | Runs Next.js's own NextNodeServer inside workerd (nodejs_compat_v2) via a Virtual FS, static chunk registry, streaming HTTP bridge, and R2+KV CacheHandler. |
legacy | Default for classic Webpack trees (engine: auto), or explicit engine: legacy | Lightweight custom Worker dispatcher with vendored React edge runtimes. |
Override per deploy with NEXTDEPLOY_CF_ENGINE=nextserver|legacy|auto or in nextdeploy.yml:
serverless:
provider: cloudflare
cloudflare:
engine: auto # auto | nextserver | legacy
compatibility_date: "2026-05-01" # validated YYYY-MM-DD (min 2025-09-01)
compatibility_flags:
- nodejs_compat # requires nodejs_compat or nodejs_compat_v2
Request Lifecycle (nextserver Engine)
Cloudflare-native fast paths stay ahead of NextNodeServer so static assets, edge auth, and pre-rendered HTML never pay Node runtime overhead:
Incoming Fetch Request (Cloudflare Edge)
│
├─ 1. Edge Protection Guard (guard.mjs)
│ IP allow/deny CIDR rules, KV rate limiting, HMAC session auth
│
├─ 2. Image Optimization (/_next/image)
│ R2 origin + Cloudflare Images / cf.image / Wasm
│
├─ 3. Static Assets (/_next/static/*, /public/*)
│ Served directly from R2 (env.ASSETS)
│
├─ 3b. Pre-rendered SSG / Fresh ISR HTML Fast Path
│ Non-RSC GET hits R2 directly (_nextdeploy/releases/<ver>/<route>.html)
│
├─ 4. Next.js NextNodeServer (Streaming HTTP Bridge)
│ • App Router & Pages Router SSR (Turbopack & Webpack)
│ • Progressive Suspense & loading.tsx streaming
│ • Client-side RSC Flight navigations (rsc: 1)
│ • API Route Handlers, Server Actions, Middleware & proxy.ts
│ • ISR & revalidateTag via CloudflareCacheHandler (R2 + KV)
│ • Custom not-found.tsx (true HTTP 404) & error.tsx boundaries
│
└─ 5. Root Public Fallback (on 404 GET)
Checks R2 for /robots.txt, /favicon.ico, /sitemap.xml, etc.
Core Architecture
1. Build-Time Virtual Filesystem (vfs.mjs + vfs_fs_shim.mjs)
NextNodeServer synchronously reads BUILD_ID, package.json, routes-manifest.json, prerender-manifest.json, and app-paths-manifest.json at startup and request time.
- Compile time (
EmitVirtualFS): Walks.next/standalone(skippingstatic/,cache/,trace/,.nft.json,.map, and files over 2 MB) and emits all manifests plus a precomputed directory index intovfs.mjs. - Runtime (
vfs_fs_shim.mjs): Aliasesfs,node:fs,fs/promises, andnode:fs/promisesto an in-memory shim supportingreadFileSync,existsSync,statSync,realpathSync,readdirSync,createReadStream, and async/promises APIs, normalizing mount prefixes (e.g./var/task/.next/...→.next/...) and raising genuineENOENTerrors on misses.
2. Static Server Chunk Registry (chunks.mjs)
Cloudflare Workers forbid eval(), new Function(), and dynamic filesystem require(expr).
- Compile time (
EmitServerChunkRegistry): Walks.next/serverand generates a static lookup table mapping every server chunk and manifest module to a static() => require(...)thunk bundled by esbuild. - Turbopack & percent-encoded path normalization: Turbopack emits runtime chunk requests like
/server/chunks/ssr/[root-of-the-server]__*.js(omitting.next/), and dynamic routes like[...slug]can arrive as percent-encodedfile://URLs.loadServerModulestrips query/hash fragments, decodesfile://URLs viadecodeURIComponent, and normalizesDIST_PREFIX(.next/) andSERVER_PREFIX(.next/server/). - Lexical dynamic-
requirescanner (dynrequire.go): An in-process esbuildOnLoadplugin runs a zero-dependency JavaScript lexical scanner over/next/dist/server/and/[turbopack]modules to rewrite non-literalrequire(expr),require?.(expr), andawait dynamicImportEsmDefault(...)calls into__ndDynRequire(expr)/__ndDynImport(expr)with VFS JSON fallback and explicitMODULE_NOT_FOUNDerrors. The scanner skips strings, comments, template literals (recursing into${...}), regex literals (including after control-flow parens and block closes), and scope-shadowedrequireidentifiers, and fails fast on unbalanced delimiters.
3. Zero-Buffering Streaming HTTP Bridge (http_bridge.mjs)
Converts Web Fetch Request into a Node IncomingMessage-compatible Readable, and pairs a Node ServerResponse-compatible EventEmitter with a Web ReadableStream.
- Headers commit on the first
writeHead(),flushHeaders(), orwrite(), immediately resolvingPromise<Response>so ReactSuspenseboundaries stream progressively to the browser. ctx.waitUntil(handlerPromise)keeps the Worker isolate alive untilres.end()closes the stream.
4. R2 + KV CloudflareCacheHandler (cf_cache_handler.mjs)
Implements Next.js's official IncrementalCache handler contract across three layers:
- L1: Per-isolate bounded LRU cache (
MAX_L1_ENTRIES = 256) for sub-millisecond warm hits without unbounded isolate memory growth. - L2: Cloudflare R2 (
env.ASSETS) under_nextdeploy/cache/<assetVersion>/<key>.jsonwith per-requestAsyncLocalStorage-isolatedctx.waitUntilwrites, guardedJSON.stringify, and automaticBufferrevival for serializedrscData. - Release Asset Fallback: On cache miss for non-
FETCHkeys, loads build-time prerendered.htmland.rscfiles from_nextdeploy/releases/<assetVersion>/<route>.{html,rsc}(preservingstatus: 404for/_not-found), allowinggenerateStaticParamsroutes to serve both full HTML and client-side RSC Flight payloads withoutNoFallbackError. - Global Registration: Registered on
globalThis[Symbol.for("@next/cache-handlers")].FetchCacheinsideinstallNextServerGlobals()so every per-routeIncrementalCacheinstance in Next.js 15/16 uses it natively without falling back toFileSystemCacheor invoking dynamicimport().
5. workerd Shims & Bundle Trimming
| Module / Surface | Treatment |
|---|---|
next/dist/server/require-hook.js | Replaced with a no-op hook map (avoids Module.prototype.require crash in ESM). |
next/dist/server/load-manifest.external.js | Replaced with a VFS + static chunk-registry shim (eliminates vm.runInNewContext). |
next/dist/server/node-environment.js | Replaced with the AsyncLocalStorage-only baseline (eliminates process.listeners crash and node:crypto warnings). |
ensureProcessCompat() & node:process | Routes process / node:process natively via workerd (plus a defense-in-depth node:* fallback so unlisted built-ins never fall through to crashing ESM __require("node:...")), and polyfills missing/throwing [unenv] properties (listeners, on/off/emit, cwd, uptime, hrtime.bigint, stdout, stderr, versions). |
| Dev / experimental / alternate-bundler runtimes | Trims *.runtime.dev.js, *-experimental.runtime.*, edge-runtime, react-dom/static, caniuse-lite, @swc/helpers, and redirects untraced alternate-bundler runtimes (app-page.runtime.prod.js ↔ app-page-turbo.runtime.prod.js) in isolated tarball builds so duplicate runtimes are never bundled. |
Native .node binaries & build isolation | Rejects genuine .node native addons on disk (Namespace: "file") at bundle time; anchors node_modules resolution strictly to the target standalone/project tree; stages into .nextdeploy-cf-staging-* and atomically promotes .nextdeploy-cf only after validation succeeds. |
6. Machine-Readable Compatibility Report (_nextdeploy/compat-report.json)
Every build emits <standalone>/.nextdeploy-cf/_nextdeploy/compat-report.json containing the resolved engine, min_compatibility_date vs configured date, bundle_sha256, raw and gzipped byte counts, compile/esbuild timings, native_builtins, partial_builtins (net, tls, dns, dns/promises, module), stubbed_app_modules vs stubbed_framework_modules, trimmed_packages, detected Next.js feature capabilities, and Free (3 MiB) / Paid (10 MiB) size or compatibility warnings.
Local Smoke Testing & Compatibility Lab
Compile and execute any real Next.js standalone build locally, or run the 7-scenario end-to-end Worker Compatibility Lab (TestWorkerCompatibilityLab):
NEXTDEPLOY_TEST_STANDALONE=/path/to/app/.next/standalone \
go test -v -count=1 ./cli/internal/serverless/cloudflare/adapter -run TestBuildWorkerBundle_RealStandaloneSmoke
go test -race -v -count=1 ./cli/internal/serverless/cloudflare/adapter -run TestWorkerCompatibilityLab