A sandboxed eval().

npm install localeval
29 downloads in the last day
75 downloads in the last week
339 downloads in the last month

Local Eval

Evaluate a string of JS code without access to the global object.

Always use that instead of eval(). Always.


localeval(code :: String, sandbox :: Object) :: Object.

localeval(code :: String,    sandbox :: Object,
          timeout :: Number, cb :: Function)

The code is a string of JS code. The sandbox contains objects which are going to be accessible in the JS code. It returns the last evaluated piece of JS code in code, if no timeout is given. Otherwise, the callback gives that result as a parameter: function(error, result) {…}.

Node example:

var localeval = require('localeval');
localeval('console.log("Do I have access to the console?")');  // Throws.

Browser example:

<!doctype html><title></title>
<script src='localeval.js'></script>
<!-- Alerts "32". -->
<script> alert(localeval('a + b', {a: 14, b: 18})) </script>

You may find an example of use in browser code in main.html.


If no timeout is given, it doesn't protect your single-threaded code against infinite loops.

That said, it protects against any security leak.

  1. All local and global variables are inaccessible.

  2. Variables defined while evaluating code don't pollute any scope.

  3. Evaluated code cannot fiddle with global object's properties. Think localeval('([]).__proto__.push = function(a) { return "nope"; }').


Trying to find a reasonable cross-environment ES5 sandbox evaluation function.

This work is licensed under the Creative Commons Attribution 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/.

npm loves you