vm2 is an advanced Node.js sandbox library designed to securely run untrusted code with controlled access to built-in modules.
Advanced vm/sandbox for Node.js
vm2 is primarily used by developers who need to execute untrusted or third-party JavaScript code safely within a Node.js environment, such as in security automation or sandboxing scenarios. It enables fine-grained control over module access and prevents code escape attempts, making it suitable for intrusion detection and secure code execution workflows.
⚠️ The vm2 project has been discontinued due to critical security vulnerabilities and should not be used in production environments. Users are strongly advised to migrate to alternative solutions such as the isolated-vm library. The original intent was to provide a secure sandbox, but recent complex escape scenarios have made maintenance unviable.
Ensure Node.js version 6 or newer is installed
Run `npm install vm2` to install the library
const {VM} = require('vm2'); const vm = new VM(); vm.run(`process.exit()`);
Runs code inside the VM sandbox where access to process.exit() is blocked, throwing a TypeError.
const vm = require('vm'); vm.runInNewContext('this.constructor.constructor("return process")().exit()');
Demonstrates that Node's native vm module allows sandbox escape and execution of process.exit(), unlike vm2.
const {VM} = require('vm2'); new VM().run('this.constructor.constructor("return process")().exit()');
Shows vm2 throwing ReferenceError when trying to access process, preventing sandbox escape.