General
Quickstart
Install Secure Exec and run untrusted JavaScript in an isolated VM in a few minutes.
Install
npm install secure-exec
Secure Exec requires Node.js 22 or newer on Linux (glibc) or macOS.
Evaluate an expression
evaluate runs one expression in a fresh VM and returns its JSON value.
import { evaluate } from "secure-exec";
// Each call runs in a fresh VM that is disposed when the call finishes.
const sum = await evaluate<number>("1 + 2");
console.log(sum.outcome === "succeeded" ? sum.value : sum.error); // 3
Pass data in
// `inputs` hands host values to the code as real objects, so data is never
// interpolated into source.
const total = await evaluate<number>(
"inputs.prices.reduce((a, b) => a + b, 0)",
{ inputs: { prices: [5, 10, 27] } },
);
console.log(total.outcome === "succeeded" ? total.value : total.error); // 42
Call host functions
Host functions run in your process, with your credentials. Each collection is a global inside the VM whose methods are async, so the guest calls them like ordinary functions. Nothing else about your process crosses into the VM.
// Inside the VM each collection is a global, and each function is async. This
// is the code a model would write.
const generated = `(async () => {
const list = await orders.list({ customer: inputs.customer });
return list.reduce((sum, order) => sum + order.amount, 0);
})()`;
// Host functions run in your process, with your credentials. The guest only
// sees their inputs and outputs. The keys name the collection and the function,
// and `execute` receives the input its own schema describes.
const total = await evaluate<number>(generated, {
hostFunctions: {
orders: {
list: {
inputSchema: z
.object({ customer: z.string() })
.describe("List a customer's orders."),
execute: ({ customer }) => [
{ customer, amount: 40 },
{ customer, amount: 2 },
],
},
},
},
inputs: { customer: "customer_123" },
timeoutMs: 5_000,
output: { capture: "stderr" },
});
console.log(total.outcome === "succeeded" ? total.value : total.stderr); // 42
Handle failures
Guest failures are returned, never thrown, so untrusted code cannot crash your process.
Next steps
- Host Functions covers schemas, errors, and Code Mode.
- VMs keep files, packages, and processes across calls.
- Execute & Evaluate explains results and options in detail.
- Permissions shows how to grant the network.