Safely sandbox and execute user submitted JavaScript?

You can use sandbox support in nodejs with vm.runInContext('js code', context), sample in api documentation:

https://nodejs.org/api/vm.html#vm_vm_runinthiscontext_code_options

const util = require('util');
const vm = require('vm');

const sandbox = { globalVar: 1 };
vm.createContext(sandbox);

for (var i = 0; i < 10; ++i) {
    vm.runInContext('globalVar *= 2;', sandbox);
}
console.log(util.inspect(sandbox));

// { globalVar: 1024 }

WARN: As pointed by "s4y" it seems to be flawled. Please look at the comments.


One alternative would be to use http://github.com/patriksimek/vm2:

$ npm install vm2

then:

const {VM} = require('vm2');
const vm = new VM();

vm.run(`1 + 1`);  // => 2

as mentioned in comments of other answers.

I don't know how secure it is, but it at least claims that it runs untrusted code securely (in its README). And I couldn't find any obvious security issues so far as solutions suggested in other answers here.