The vm module
suggest changeThe built-in node:vm module compiles and runs JavaScript code given as a string. Unlike eval(), it can run that code inside a separate context: a fresh global object with its own built-ins (Object, Array, JSON, Math ...), and only the variables you choose to expose.
Typical uses:
- evaluating user-supplied expressions or formulas (spreadsheet cells, rules, filters)
- configuration files written in JavaScript
- template engines and code generators
- REPLs, playgrounds, test runners and module loaders (Node's own CommonJS loader and REPL are built on it)
- running code with a time limit
One warning up front, repeated later: vm is not a security sandbox. It isolates globals, not privileges. Don't use it to run code from people you don't trust.
Running code in a new context
The quickest way in is vm.runInNewContext(code, sandbox). The properties of sandbox become global variables for the code, and the value of the last expression is returned:
import vm from 'node:vm';
const result = vm.runInNewContext('x * y + 1', { x: 6, y: 7 });
console.log(result); // 43
// the code can't see your module's variables or Node globals
const secret = 'hunter2';
console.log(vm.runInNewContext('typeof secret')); // undefined
console.log(vm.runInNewContext('typeof process')); // undefined
console.log(vm.runInNewContext('typeof require')); // undefined
Each call creates a brand new context, which is relatively expensive (it allocates a whole new set of built-ins). When you run code more than once, create the context yourself and reuse it.
Contexts: createContext and runInContext
vm.createContext(obj) "contextifies" an object: it becomes the global object for code run in that context. Changes the code makes to globals show up on your object, and changes you make to the object are visible to the code:
import vm from 'node:vm';
const ctx = vm.createContext({ count: 0, items: [] });
vm.runInContext('count += 1; items.push("a")', ctx);
vm.runInContext('count += 1; items.push("b")', ctx);
console.log(ctx.count, ctx.items); // 2 [ 'a', 'b' ]
ctx.count = 100;
console.log(vm.runInContext('count', ctx)); // 100
// var and function declarations become properties of the context object
vm.runInContext('var greeting = "hi"; function double(n) { return n * 2 }', ctx);
console.log(ctx.greeting); // hi
console.log(ctx.double(21)); // 42
console.log(vm.isContext(ctx)); // true
console.log(vm.isContext({})); // false
Top-level let, const and class declarations behave like they do in a browser <script>: they persist between runs in the same context, but they are not properties of the global object:
import vm from 'node:vm';
const ctx = vm.createContext({});
vm.runInContext('let total = 10; const LIMIT = 3', ctx);
console.log(ctx.total); // undefined
console.log(vm.runInContext('total', ctx)); // 10
console.log(vm.runInContext('LIMIT', ctx)); // 3
// re-declaring is an error, just like in a single script
try {
vm.runInContext('let total = 0', ctx);
} catch (err) {
console.log(err.name, err.message);
// SyntaxError Identifier 'total' has already been declared
}
This persistence is what makes a REPL possible: every line runs in the same context and sees what earlier lines defined.
vm.createContext() with no argument creates an empty context and returns the new global object.
Exposing functions and console
A new context has none of Node's globals: no console that prints to the terminal, no setTimeout, no process, no Buffer, no require. If code needs something, put it in the context object:
import vm from 'node:vm';
const ctx = vm.createContext({
console, // share our console
log: (...args) => console.log('[script]', ...args),
fetchPrice: (sku) => ({ apple: 1.2, pear: 0.9 })[sku] ?? 0,
});
vm.runInContext(`
const total = fetchPrice('apple') * 3 + fetchPrice('pear');
log('total is', total.toFixed(2));
console.log('typeof setTimeout:', typeof setTimeout);
`, ctx);
// [script] total is 4.50
// typeof setTimeout: undefined
Built-ins defined by the JavaScript language itself (Math, JSON, Date, Promise, Map, RegExp, Intl, etc.) are always available, because every context gets its own copy of them.
Compiling once with vm.Script
vm.Script compiles code once so you can run it many times, in one or many contexts. Compilation is usually the costly part, so this is the way to go for code you run repeatedly:
import vm from 'node:vm';
const script = new vm.Script('price * qty * (1 - discount)', {
filename: 'order-total.vm.js', // shows up in stack traces
});
const orders = [
{ price: 10, qty: 3, discount: 0 },
{ price: 25, qty: 2, discount: 0.1 },
{ price: 4, qty: 10, discount: 0.25 },
];
for (const order of orders) {
const ctx = vm.createContext(order);
console.log(script.runInContext(ctx));
}
// 30
// 45
// 30
A Script has three run methods:
| Method | Runs the code in |
|---|---|
script.runInContext(ctx) |
an existing context |
script.runInNewContext(obj) |
a new context created from obj |
script.runInThisContext() |
the main context (real globalThis) |
The module-level functions vm.runInContext(), vm.runInNewContext() and vm.runInThisContext() are shortcuts that create a Script and immediately run it.
The filename option (and lineOffset / columnOffset) makes errors point at something meaningful:
import vm from 'node:vm';
const code = `
function check(n) {
if (n < 0) throw new Error('negative: ' + n);
return n;
}
check(-5);
`;
try {
vm.runInNewContext(code, {}, { filename: 'rules/check.js' });
} catch (err) {
// Node prepends a source excerpt (file:line, code, ^) to the stack; skip it
const lines = err.stack.split('\n');
const start = lines.findIndex((l) => l.startsWith('Error'));
console.log(lines.slice(start, start + 3).join('\n'));
}
// Error: negative: -5
// at check (rules/check.js:3:20)
// at rules/check.js:6:1
Syntax errors are thrown when the code is compiled, before anything runs:
import vm from 'node:vm';
try {
new vm.Script('let x = ;', { filename: 'bad.js' });
} catch (err) {
console.log(err.name, '-', err.message); // SyntaxError - Unexpected token ';'
}
runInThisContext vs. eval
vm.runInThisContext(code) runs code in the main context, so it sees real globals (globalThis, process, console), but unlike eval() it can't see the local variables of the function or module that calls it:
import vm from 'node:vm';
let localVar = 'initial';
eval('localVar = "changed by eval"');
console.log(localVar); // changed by eval
vm.runInThisContext('localVar = "changed by vm"');
console.log(localVar); // changed by eval
console.log(globalThis.localVar); // changed by vm (a new global was created)
vm.runInThisContext('console.log(typeof process)'); // object
That makes it useful for running generated code that should behave like a top-level script, without accidentally capturing whatever variables happen to be in scope.
Compiling functions with vm.compileFunction
vm.compileFunction(body, params) turns a string into a real function, much like new Function(...), but with options for the file name, line offset and the context it belongs to:
import vm from 'node:vm';
const add = vm.compileFunction('return a + b', ['a', 'b']);
console.log(add(2, 3)); // 5
// a function whose globals come from a context
const ctx = vm.createContext({ TAX: 0.23 });
const gross = vm.compileFunction('return net * (1 + TAX)', ['net'], {
parsingContext: ctx,
filename: 'pricing.js',
});
console.log(gross(100)); // 123
This is essentially how Node's CommonJS loader works: it wraps each file in a function with exports, require, module, __filename and __dirname parameters. A tiny version of that:
import vm from 'node:vm';
import path from 'node:path';
import { createRequire } from 'node:module';
function loadCommonJS(source, filename) {
const wrapper = vm.compileFunction(
source,
['exports', 'require', 'module', '__filename', '__dirname'],
{ filename },
);
const module = { exports: {} };
const require = createRequire(filename);
wrapper.call(module.exports, module.exports, require, module,
filename, path.dirname(filename));
return module.exports;
}
const source = `
const os = require('node:os');
module.exports = { platform: () => os.platform(), name: __filename };
`;
const mod = loadCommonJS(source, path.resolve('virtual-module.js'));
console.log(mod.platform()); // e.g. linux
console.log(path.basename(mod.name)); // virtual-module.js
See also Add new extensions to require.
Time limits
The timeout option (in milliseconds) stops code that runs too long, such as an infinite loop. The code is terminated and an error with code ERR_SCRIPT_EXECUTION_TIMEOUT is thrown:
import vm from 'node:vm';
try {
vm.runInNewContext('while (true) {}', {}, { timeout: 50 });
} catch (err) {
console.log(err.code); // ERR_SCRIPT_EXECUTION_TIMEOUT
console.log(err.message); // Script execution timed out after 50ms
}
console.log('still running');
The timeout only covers synchronous execution. By default, promise callbacks (microtasks) queued by the code run later on the main microtask queue, outside the timeout, so this would hang your process:
// DON'T: the loop runs after runInContext returns, with no timeout
vm.runInNewContext('Promise.resolve().then(() => { while (true) {} })', {}, { timeout: 50 });
Create the context with microtaskMode: 'afterEvaluate' to make microtasks run as part of the evaluation, inside the time limit:
import vm from 'node:vm';
const ctx = vm.createContext({}, { microtaskMode: 'afterEvaluate' });
try {
vm.runInContext('Promise.resolve().then(() => { while (true) {} })', ctx, { timeout: 50 });
} catch (err) {
console.log(err.code); // ERR_SCRIPT_EXECUTION_TIMEOUT
}
Timers and I/O are a separate problem: if you pass setTimeout or async functions into the context, their callbacks run on the main event loop and no timeout applies to them.
There's also breakOnSigint: true, which lets Ctrl+C interrupt a long-running script (with an ERR_SCRIPT_EXECUTION_INTERRUPTED error) instead of killing the process.
Disabling eval and WebAssembly inside a context
codeGeneration options on createContext turn off eval(), new Function() and WebAssembly compilation for code in that context:
import vm from 'node:vm';
const ctx = vm.createContext({}, {
name: 'no-eval',
codeGeneration: { strings: false, wasm: false },
});
console.log(vm.runInContext('1 + 2', ctx)); // 3
try {
vm.runInContext('eval("1 + 2")', ctx);
} catch (err) {
console.log(err.name, '-', err.message);
// EvalError - Code generation from strings disallowed for this context
}
Objects from another context
Each context has its own set of built-in constructors, so objects created inside a context are not instanceof the main context's classes. This trips people up all the time:
import vm from 'node:vm';
const arr = vm.runInNewContext('[1, 2, 3]');
console.log(arr instanceof Array); // false: a different Array constructor
console.log(Array.isArray(arr)); // true: works across contexts
const obj = vm.runInNewContext('({ a: 1 })');
console.log(obj.constructor === Object); // false
try {
vm.runInNewContext('null.x');
} catch (err) {
console.log(err instanceof TypeError); // false
console.log(err.name); // TypeError
}
Practical rules:
- check arrays with
Array.isArray(), notinstanceof Array - check errors with
err.name/err.code, orError.isError(err)(Node.js 24+), notinstanceof - to get plain main-context values out, copy them with
structuredClone()(orJSON.parse(JSON.stringify(...))for JSON-compatible data)
import vm from 'node:vm';
const raw = vm.runInNewContext('({ list: [1, 2], when: new Date(0) })');
const copy = structuredClone(raw);
console.log(copy.list instanceof Array, copy.when instanceof Date); // true true
Example: a safe-ish expression evaluator
A common use is evaluating short formulas defined in configuration or by admins, with only a whitelisted set of helpers. Compile each formula once, reuse a context, cap execution time, and turn off code generation:
import vm from 'node:vm';
function makeEvaluator(helpers = {}) {
const ctx = vm.createContext(
{ ...helpers },
{ codeGeneration: { strings: false, wasm: false }, microtaskMode: 'afterEvaluate' },
);
const cache = new Map();
return function evaluate(expr, vars = {}) {
let script = cache.get(expr);
if (!script) {
// wrap in parens so only an expression is accepted, not statements
script = new vm.Script(`(${expr}\n)`, { filename: 'formula' });
cache.set(expr, script);
}
Object.assign(ctx, vars);
try {
return script.runInContext(ctx, { timeout: 20 });
} finally {
for (const key of Object.keys(vars)) delete ctx[key];
}
};
}
const evaluate = makeEvaluator({
round2: (n) => Math.round(n * 100) / 100,
clamp: (n, lo, hi) => Math.min(hi, Math.max(lo, n)),
});
console.log(evaluate('round2(price * 1.23)', { price: 19.99 })); // 24.59
console.log(evaluate('clamp(score, 0, 100)', { score: 140 })); // 100
console.log(evaluate('qty > 10 ? "bulk" : "retail"', { qty: 12 })); // bulk
try {
evaluate('price', {}); // variables from earlier calls are not left behind
} catch (err) {
console.log(err.name, '-', err.message); // ReferenceError - price is not defined
}
This is fine for formulas written by your own team. It is not enough for arbitrary code from the internet, for the reasons below.
vm is not a security mechanism
The Node.js documentation says it plainly: the vm module is not a security mechanism. A context separates globals, but it runs in the same process, on the same thread, with the same privileges. The classic escape uses the fact that the context's global object was created by your code, in your context:
import vm from 'node:vm';
const leaked = vm.runInNewContext(`
const OuterFunction = this.constructor.constructor;
const proc = OuterFunction('return process')();
proc.version
`, {});
console.log(leaked); // e.g. v24.x.x, so the code got hold of the real process object
Any object or function you pass in can be used the same way, through .constructor or a thrown error. Once code has process, it can read environment variables, load modules, spawn processes and delete files. Even without an escape, untrusted code can allocate memory until the process crashes, and timeout doesn't help with async code that loops through timers you gave it.
If you need to run untrusted code, use real isolation:
- a separate process or container with restricted OS permissions (see Child Process)
- a worker thread with
resourceLimitsto cap memory, combined with process-level isolation (see Multithreading) - Node's permission model (
node --permission --allow-fs-read=...) to limit what a process can touch - a library built on separate V8 isolates, such as
isolated-vm
ES modules in vm
vm.Script and friends run classic scripts, so import / export statements are syntax errors. There is an API for ES modules (vm.SourceTextModule, vm.SyntheticModule), but as of Node.js 24 it is still experimental and requires the --experimental-vm-modules flag. Most programs don't need it; if the code just needs a few modules, pass them in through the context object.
Summary
| Task | Code |
|---|---|
| evaluate in a fresh context | vm.runInNewContext(code, { x: 1 }) |
| create a reusable context | const ctx = vm.createContext(obj) |
| run in a context | vm.runInContext(code, ctx) |
| compile once, run many times | new vm.Script(code, { filename }).runInContext(ctx) |
| run in main context without local scope | vm.runInThisContext(code) |
| build a function from a string | vm.compileFunction(body, ['a', 'b']) |
| limit execution time | { timeout: 100 } + microtaskMode: 'afterEvaluate' |
disable eval inside |
createContext(obj, { codeGeneration: { strings: false } }) |
| check arrays from a context | Array.isArray(value) |
| copy results to main context | structuredClone(value) |