Evaluate JS manifests with compileFunction instead of a new context
What?
evalManifest now runs JS manifests (_client-reference-manifest.js) with vm.compileFunction instead of vm.runInNewContext.
Why?
runInNewContext creates a new V8 context for every manifest. Every object the manifest creates belongs to that context's realm, through its prototypes. So the cached manifest keeps the whole context, its global and all builtins, alive.
Measured on Node with synthetic manifests:
- Retained memory: about 145 KB per cached manifest, compared with about 0.5 KB with
compileFunction. Holding only the manifest object, rather than the sandbox, retains the same 145 KB. A production server caches one manifest per route it has served, so this adds up with many routes. - Load time: about 0.15–0.25 ms faster per manifest from not creating a context. For large manifests, parsing and evaluation dominate.
How?
The script runs as the body of a function whose globalThis and process parameters shadow the real ones:
compileFunction(content, ['globalThis', 'process'], { filename: path })(
manifestGlobal,
{ env: { NEXT_DEPLOYMENT_ID: process.env.NEXT_DEPLOYMENT_ID } }
)
Both manifest formats register through the globalThis. identifier, so they work unchanged:
- Turbopack:
(globalThis.__RSC_MANIFEST ??= {})[page] = m - Webpack:
globalThis.__RSC_MANIFEST = (globalThis.__RSC_MANIFEST || {}); ...
The real global is never written, and the result object has the same shape as before, minus the process key. The manifest's objects and arrays now belong to the server's realm, so instanceof Array works on them.
Unit tests in load-manifest.test.ts cover the following:
- The real global is not touched.
- Only
NEXT_DEPLOYMENT_IDis exposed. - The result is frozen and cached.
- An empty file still throws.
test/e2e/app-dir/rsc-basic passes with next start on Turbopack and webpack.