← Back to Node.js, page 7

nodejs-0124 · Hard senior

What does the node:vm module do, and why is it not a security sandbox?

The vm module compiles and runs code in a separate V8 context with its own global object, optionally with a timeout. It is useful for templates, configuration scripts and tests, but it is not a security boundary: code can reach the host through any object you pass in, a timeout cannot stop everything, and memory is shared. Run untrusted code in a separate process, container or an isolate-based library.

Full answer

What vm gives you

  • vm.runInNewContext(code, sandbox, options) or vm.createContext(sandbox) with vm.runInContext. The code sees only the properties of the sandbox as globals. It does not see require, process or module.
  • vm.Script compiles once and runs many times (script.runInContext). Use it for hot paths.
  • The timeout option stops synchronous infinite loops (error code ERR_SCRIPT_EXECUTION_TIMEOUT).
  • vm.runInThisContext runs code in the main global scope, without access to local variables, like indirect eval or new Function. Direct eval can see local variables.
  • vm.compileFunction builds a function from a string with chosen parameters.

Why it is not a sandbox

  • Objects you pass in connect back to the host. sandbox.log.constructor is the host Function constructor, so code can run Function('return process')() and get the real process, then use child_process.
  • The timeout covers only synchronous code. Promises and timers created inside can still run later. Microtask loops and native calls may not be interrupted.
  • It shares the heap and the process. Memory bombs and crashes affect the host.
  • The Node documentation says clearly not to use vm for untrusted code.

Safer options

  • A child process or container with limited privileges and a hard timeout and memory limit.
  • worker_threads with resourceLimits (isolates memory, not capabilities) plus the permission model.
  • Libraries based on separate isolates (for example isolated-vm), or WebAssembly for logic you control.
  • Avoid running user code at all: use a safe expression language or a data-driven rule format.

Legitimate uses: running your own configuration or build scripts, REPL-like tools, template engines, and test runners that need clean globals.

javascript
const vm = require('node:vm');

// 1. A new context has its own globals.
const sandbox = { price: 100, tax: 0.18 };
console.log('total:', vm.runInNewContext('price * (1 + tax)', sandbox));
console.log('process visible inside:', vm.runInNewContext('typeof process', {}));
console.log('require visible inside:', vm.runInNewContext('typeof require', {}));

// 2. Globals created by the code stay in the context between runs.
const context = vm.createContext({ log: [] });
vm.runInContext('var counter = 0; function bump() { counter += 1; log.push(counter); }', context);
vm.runInContext('bump(); bump();', context);
console.log('counter inside context:', context.counter, '| log:', context.log.join(','));

// 3. Compile once, run many times.
const script = new vm.Script('value * 2');
console.log('script results:', [1, 2, 3].map((value) => script.runInNewContext({ value })).join(','));

// 4. The timeout stops a synchronous infinite loop.
try { vm.runInNewContext('while (true) {}', {}, { timeout: 50 }); } catch (err) { console.log('timeout ->', err.code); }

// 5. Why it is not a security boundary: a host function passed in leads back to the host.
const escaped = vm.runInNewContext("hostFn.constructor('return typeof process')()", { hostFn: () => {} });
console.log('code reached the host process through a passed-in function:', escaped === 'object');

// 6. Scope differences
const local = 'local value';
console.log('direct eval sees local:', eval('typeof local'));
console.log('runInThisContext sees local:', vm.runInThisContext('typeof local'));
console.log('new Function sees local:', new Function('return typeof local')());

The script runs code in separate contexts, uses the timeout, and then shows the escape through a function passed into the sandbox. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): total: 118 process visible inside: undefined require visible inside: undefined counter inside context: 2 | log: 1,2 script results: 2,4,6 timeout -> ERR_SCRIPT_EXECUTION_TIMEOUT code reached the host process through a passed-in function: true direct eval sees local: string runInThisContext sees local: undefined new Function sees local: undefined

Key points

  • vm runs code in a separate global context.
  • timeout interrupts synchronous infinite loops.
  • Objects passed into the sandbox allow escape to the host.
  • vm is not a security boundary.
  • Use processes, containers or isolates for untrusted code.

Common mistakes

  • Using vm.runInNewContext on user input and believing it is safe.
  • Passing host objects, functions or console into the sandbox without thinking about the escape.
  • Relying on timeout to stop promises or timers.
  • Compiling the same code again in a hot loop instead of using vm.Script.
  • Confusing runInThisContext with direct eval.

Follow-ups

  • How would you run untrusted user code safely in a Node.js service?
  • What does vm.measureMemory do?
  • How does a template engine use vm?

Tips

  • Say 'not a security boundary' without being asked.
  • Give the host function escape as proof.
  • Offer the process or container alternative.