vm2 is a sandbox that can run untrusted code with whitelisted Node's built-in modules.
Before using vm2, you should understand how it works and its limitations.
vm2 attempts to sandbox untrusted JavaScript code within the same Node.js process as your application. It does this through a complex network of Proxies that intercept and mediate every interaction between the sandbox and the host environment.
JavaScript is an extraordinarily dynamic language. Objects can be accessed through prototype chains, constructors can be reached via error objects, symbols provide protocol hooks, and async execution creates timing windows. The sheer number of ways to traverse from one object to another in JavaScript makes building an airtight in-process sandbox extremely difficult.
We are honest about this reality: Despite our best efforts, researchers and security professionals continuously discover new ways to escape the vm2 sandbox. We actively patch these vulnerabilities as they are reported, but the cat-and-mouse nature of in-process sandboxing means that:
If you require stronger isolation guarantees, consider these alternatives that provide true process or hardware-level isolation:
| Solution | Approach | Performance | Trade-offs |
|---|---|---|---|
| isolated-vm | Separate V8 isolates (different V8 heap) | Fast | In maintenance mode; requires manual V8 updates |
| Separate process / Worker | child_process or Worker threads with limited permissions |
Medium | Higher IPC overhead; data must be serialized |
| Containers / VMs | Docker, gVisor, Firecracker | Slow | Startup overhead; resource-heavy |
| Managed services | Cloud-based code execution (e.g., AWS Lambda, Cloudflare Workers) | Variable | Network latency; external dependency |
vm2 can be suitable when: - You need tight integration with host objects and fast synchronous communication - The untrusted code comes from a relatively trusted source (e.g., internal tools, plugin systems with vetted authors) - You combine vm2 with other security layers (network isolation, filesystem restrictions, resource limits) - You accept the risk and actively monitor for security updates
If you're running code from completely untrusted sources (e.g., arbitrary user submissions), we strongly recommend using a solution with stronger isolation guarantees.
For an in-depth look at vm2’s internals, see the CONTRIBUTING.md file.
Try it yourself:
import { runInNewContext } from "node:vm";
runInNewContext('this.constructor.constructor("return process")().exit()');
console.log('Never gets executed.');
import { VM } from 'vm2';
new VM().run('this.constructor.constructor("return process")().exit()');
// Throws ReferenceError: process is not defined
npm install vm2
import { VM } from 'vm2';
const vm = new VM();
vm.run(`process.exit()`); // TypeError: process.exit is not a function
import { NodeVM } from 'vm2';
const vm = new NodeVM({
require: {
external: true,
root: './',
},
});
vm.run(
`
var request = require('request');
request('http://www.google.com', function (error, response, body) {
console.error(error);
if (!error && response.statusCode == 200) {
console.log(body); // Show the HTML for the Google homepage.
}
});
`,
'vm.js',
);
VM is a simple sandbox to synchronously run untrusted code without the require feature. Only JavaScript built-in objects and Node's Buffer are available. Scheduling functions (setInterval, setTimeout and setImmediate) are not available by default.
Options:
timeout - Script timeout in milliseconds. WARNING: You might want to use this option together with allowAsync=false. Further, operating on returned objects from the sandbox can run arbitrary code and circumvent the timeout. One should test if the returned object is a primitive with typeof and fully discard it (doing logging or creating error messages with such an object might also run arbitrary code again) in the other case.sandbox - VM's global object.compiler - javascript (default), typescript, coffeescript or custom compiler function. The library expects you to have compiler pre-installed if the value is set to typescript or coffeescript.eval - If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc.) will throw an EvalError (default: true).wasm - If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError (default: true). Note: WebAssembly.JSTag is removed inside the sandbox for security reasons, so wasm code cannot catch JavaScript exceptions.allowAsync - If set to false any attempt to run code using async will throw a VMError (default: true).bufferAllocLimit - Maximum size in bytes for a single Buffer.alloc / Buffer.allocUnsafe / Buffer.allocUnsafeSlow / Buffer(N) / new Buffer(N) request from inside the sandbox. Requests that exceed this cap throw a RangeError synchronously without performing the host allocation. Default: Infinity (no cap, fully backwards-compatible). Embedders running untrusted code in memory-constrained environments (Docker / Kubernetes / Lambda / serverless) should opt into a finite cap (e.g. 32 * 1024 * 1024) as part of layered DoS defense, the same way they opt into timeout. See Hardening recommendations below.IMPORTANT: Timeout is only effective on synchronous code that you run through run. Timeout does NOT work on any method returned by VM. There are some situations when timeout doesn't work - see #244.
import { VM } from 'vm2';
const vm = new VM({
timeout: 1000,
allowAsync: false,
sandbox: {},
});
vm.run('process.exit()'); // throws ReferenceError: process is not defined
You can also retrieve values from VM.
let number = vm.run('1337'); // returns 1337
TIP: See tests for more usage examples.
Unlike VM, NodeVM allows you to require modules in the same way that you would in the regular Node's context.
Options:
console - inherit to enable console, redirect to redirect to events, off to disable console (default: inherit).sandbox - VM's global object.compiler - javascript (default), typescript, coffeescript or custom compiler function (which receives the code, and it's file path). The library expects you to have compiler pre-installed if the value is set to typescript or coffeescript.eval - If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc.) will throw an EvalError (default: true).wasm - If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError (default: true). Note: WebAssembly.JSTag is removed inside the sandbox for security reasons, so wasm code cannot catch JavaScript exceptions.bufferAllocLimit - Same semantics as on VM — maximum size in bytes for a single Buffer.alloc family request from inside the sandbox. Default: Infinity. See Hardening recommendations.sourceExtensions - Array of file extensions to treat as source code (default: ['js']).require - true, an object or a Resolver to enable require method (default: false).require.external - Values can be true, an array of allowed external modules, or an object (default: false). All paths matching /node_modules/${any_allowed_external_module}/(?!/node_modules/) are allowed to be required.require.external.modules - Array of allowed external modules. Also supports wildcards, so specifying ['@scope/*-ver-??], for instance, will allow using all modules having a name of the form @scope/something-ver-aa, @scope/other-ver-11, etc. The * wildcard does not match path separators.require.external.transitive - Boolean which indicates if transitive dependencies of external modules are allowed (default: false). WARNING: When a module is required transitively, any module is then able to require it normally, even if this was not possible before it was loaded.require.builtin - Array of allowed built-in modules, accepts ["*"] for all (default: none). WARNING: "*" can be dangerous as new built-ins can be added.require.root - Restricted path(s) where local modules can be required (default: every path).require.mock - Collection of mock modules (both external or built-in).require.context - host (default) to require modules in the host and proxy them into the sandbox. sandbox to load, compile, and require modules in the sandbox. callback(moduleFilename, ext) to dynamically choose a context per module. The default will be sandbox is nothing is specified. Except for events, built-in modules are always required in the host and proxied into the sandbox.require.import - An array of modules to be loaded into NodeVM on start.require.resolve - An additional lookup function in case a module wasn't found in one of the traditional node lookup paths.require.customRequire - Use instead of the require function to load modules from the host.require.strict - false to not force strict mode on modules loaded by require (default: true).require.fs - Custom file system implementation.nesting - WARNING: Allowing this is a security risk as scripts can create a NodeVM which can require any host module. true to enable VMs nesting (default: false).wrapper - commonjs (default) to wrap script into CommonJS wrapper, none to retrieve value returned by the script.argv - Array to be passed to process.argv.env - Object to be passed to process.env.strict - true to loaded modules in strict mode (default: false).IMPORTANT: Timeout is not effective for NodeVM so it is not immune to while (true) {} or similar evil.
REMEMBER: The more modules you allow, the more fragile your sandbox becomes.
import { NodeVM } from 'vm2';
const vm = new NodeVM({
console: 'inherit',
sandbox: {},
require: {
external: true,
builtin: ['fs', 'path'],
root: './',
mock: {
fs: {
readFileSync: () => 'Nice try!',
},
},
},
});
// Sync
let functionInSandbox = vm.run('module.exports = function(who) { console.log("hello "+ who); }');
functionInSandbox('world');
// Async
let functionWithCallbackInSandbox = vm.run('module.exports = function(who, callback) { callback("hello "+ who); }');
functionWithCallbackInSandbox('world', greeting => {
console.log(greeting);
});
When wrapper is set to none, NodeVM behaves more like VM for synchronous code.
assert.ok(vm.run('return true') === true);
TIP: See tests for more usage examples.
To load modules by relative path, you must pass the full path of the script you're running as a second argument to vm's run method if the script is a string. The filename is then displayed in any stack traces generated by the script.
vm.run('require("foobar")', '/data/myvmscript.js');
If the script you are running