isolated-function
Why isolated-function?
Sometimes your application needs to let users customize a piece of behavior with JavaScript.
That code might be a function template for an AI agent, a customer-defined workflow, a plugin, a webhook transform, or an automation rule. You provide the shape of the function and the runtime context; users provide the custom logic. You want the useful part: programmable behavior without turning the rest of your application into the execution environment.
isolated-function gives you a small API for turning user-customizable function templates into controlled executions:
- give it a function or generated function template
- pass runtime arguments into it
- choose what it is allowed to do
- set memory and timeout limits
- run it
- get back the result, logs, errors, and timing data
It is useful when your product needs user-defined logic, but you still want a narrow execution contract around what that logic can receive, return, import, and access.
What it does
At a high level, isolated-function wraps a JavaScript function and runs it away from your main process.
The core use case is giving your product a controlled function template that users can customize. Your application owns the template, runtime arguments, dependencies, permissions, timeout, memory, result shape, logging, and cleanup. Users only customize the part of the function you intentionally expose.
This is the pattern used by @browserless/function: it lets users build functions that can access a Puppeteer page and related browser context, then runs those functions through isolated-function.
It can:
- run untrusted code in a separate process
- restrict filesystem, network, worker, and child-process access through the Node.js Permission Model
- stop runaway code with memory, wall-clock, and CPU limits
- detect dependencies used by the function
- install and bundle those dependencies with esbuild
- reuse installed dependencies across executions
- allow only the packages you explicitly trust
- return profiling data for compile, spawn, run, and total time
What it is not
isolated-function is not a virtual machine, microVM, container runtime, or hypervisor-based sandbox.
It isolates JavaScript by running it in a separate Node.js process with Node.js permissions and resource limits. That is useful for many plugin, workflow, webhook, and AI-agent use cases, but it is not the same security boundary as KVM, Firecracker, Kata Containers, gVisor, or another VM-backed isolation layer.
If you need to execute hostile multi-tenant code, use isolated-function behind a stronger runtime boundary such as a locked-down container, gVisor, Kata Containers, Firecracker, or another hypervisor-backed execution environment.
Installation
pnpm add isolated-function
Your first isolated function
First create an isolated-function instance. You can call it with no options:
const isolatedFunction = require('isolated-function')()
Or pass shared options that apply to every function created from that instance:
const isolatedFunction = require('isolated-function')({
tmpdir: '/tmp/isolated-function-deps',
nodePaths: [require('path').resolve(__dirname, 'node_modules')]
})
- tmpdir controls where isolated-function installs and reuses dependencies.
- nodePaths points to directories where dependencies may already be installed, so matching packages can skip installation.
Then wrap a normal JavaScript function:
const sum = isolatedFunction((y, z) => y + z, {
memory: 128, // in MB
timeout: 10000 // in milliseconds
})
Now call it like any other async function:
const { value, profiling } = await sum(3, 2)
console.log(value) // 5
console.log(profiling.total) // total execution time in milliseconds
When your application shuts down, clean up the shared dependency cache:
await isolatedFunction.teardown()
That is the basic loop: create a sandboxed function, run it, read the result.
Minimal privilege execution
By default, hosted code runs with minimal privileges. If it tries to use a restricted capability, isolated-function fails the execution instead of giving the code access.
For example, this function tries to write to /etc/passwd:
const fn = isolatedFunction(() => {
const fs = require('fs')
fs.writeFileSync('/etc/passwd', 'foo')
})
await fn()
// => PermissionError: Access to 'FileSystemWrite' has been restricted.
The function ran in its own process, and the filesystem write was blocked.
The child does not inherit the parent environment. Only PATH and the sandbox NODE_OPTIONS are passed. Values the function needs should be arguments, not env vars.
Granting specific permissions
Some functions need more access. Grant only the permissions that function needs with allow.permissions.
const fn = isolatedFunction(
() => {
const { execSync } = require('child_process')
return execSync('echo hello').toString().trim()
},
{
allow: { permissions: ['child-process'] }
}
)
const { value } = await fn()
console.log(value) // 'hello'
See #allow.permissions for the full list.
Auto install dependencies
Hosted code can bring its own dependencies. isolated-function parses require and import calls, installs the packages, and bundles the function before running it.
const isEmoji = isolatedFunction(input => {
/* this dependency only exists inside the isolated function */
const isEmoji = require('is-standard-emoji@1.0.0') // default is latest
return isEmoji(input)
})
await isEmoji('🙌') // => true
await isEmoji('foo') // => false
A file inside a package goes after the version, the same way as without one: require('lodash@4.17.21/fp') installs lodash@4.17.21 and loads lodash/fp. The subpath split applies after a version, a ^ or ~ range, an x-range, or latest, so require('isarray@juliangruber/isarray') is still a GitHub dependency. A path that leaves the package (.., ., an empty segment) or a relative or absolute path is a DependencyNameError. A module is bundled only when its name is a string literal: a computed one, such as require('lo' + 'dash'), fails the build, except for Node.js builtins, which resolve at run time under the permission model.
The hosted code and its dependencies are bundled into a single file with esbuild before execution.
Dependencies are installed into a shared persistent directory and reused across invocations, so only the first call that requires a given package pays the install cost.
Installation runs in-process through upm, so no package manager needs to be on the PATH. Package lifecycle scripts never run, a required package without a version resolves to its latest release with no minimum release age, and downloaded packages are cached in upm's shared store (~/.upm/store, or UPM_STORE).
Restricting allowed dependencies
If the code is untrusted, do not let it install arbitrary packages. Use allow.dependencies to define the packages it may use:
const fn = isolatedFunction(
input => {
const isEmoji = require('is-standard-emoji')
return isEmoji(input)
},
{
allow: { dependencies: ['is-standard-emoji', 'lodash'] }
}
)
await fn('🙌') // => true
If the code tries to require a package not in the allowed list, a DependencyUnallowedError is thrown before any package install happens:
const fn = isolatedFunction(
() => {
const malicious = require('malicious-package')
return malicious()
},
{
allow: { dependencies: ['lodash'] }
}
)
await fn()
// => DependencyUnallowedError: Dependency 'malicious-package' is not in the allowed list
Security Note: Even with the sandbox, arbitrary package installation is dangerous because packages can execute code during installation via preinstall/postinstall scripts. Installation never runs those lifecycle scripts, but providing an allow.dependencies whitelist is the recommended approach for running untrusted code.
Execution profiling
Any hosted code execution will be run in their own separate process:
/** make a function to consume ~128MB */
const fn = isolatedFunction(() => {
const storage = []
const oneMegabyte = 1024 * 1024
while (storage.length < 78) {
const array = new Uint8Array(oneMegabyte)
for (let ii = 0; ii < oneMegabyte; ii += 4096) {
array[ii] = 1
}
storage.push(array)
}
})
const { value, profiling } = await fn()
console.log(profiling)
// {
// cpu: 42.5,
// memory: {
// total: 128204800,
// used: 85198848,
// heap: 2831776,
// external: 83961856
// },
// phases: {
// install: 0,
// build: 12,
// spawn: 48,
// run: 54,
// total: 102
// }
// }
Each execution includes profiling data:
- cpu — CPU time (user + system) consumed by the process, in milliseconds.
- memory — Memory breakdown, in bytes, sampled when the function returns. No single number describes the memory a function used, so each field answers a different question:
- total — Resident set size of the whole isolate process. Includes the ~43MB Node.js runtime baseline, so it is never zero.
- used —
total minus the baseline measured before the function ran. This is the part attributable to the function.
- heap — V8 heap in use. This is the only field bounded by the
memory limit.
- external — Off-heap memory (
Buffer, ArrayBuffer, typed arrays). Not bounded by the memory limit, and invisible to total until the pages are written to.
- phases — Wall-clock time breakdown of each execution stage, in milliseconds:
- install — Time installing npm dependencies the code requires.
0 when it requires none, or they are already present.
- build — Time bundling the code with esbuild. Each
instance(code) call builds again; with slot, it is only the time to fill an already built shell.
- spawn — Process creation, Node.js boot, and template setup overhead.
- run — User function execution time.
- total — End-to-end wall-clock time.
Resource limits
You can limit a isolated-function with memory:
const fn = isolatedFunction(() => {
const storage = []
while (true) storage.push('x'.repeat(1024))
}, { memory: 64 })
await fn()
// => MemoryError: Out of memory
[!IMPORTANT]
The memory limit bounds the V8 heap (profiling.memory.heap), which is where ordinary objects and strings live. Off-heap memory (profiling.memory.external) — Buffer, ArrayBuffer, and typed arrays — can grow past that number. On Linux, when sh is on PATH, the process also gets a virtual-memory ceiling above the limit, so an allocation past the ceiling fails. A SIGKILL the host did not issue, including one from a cgroup, is reported as MemoryError. The host's wall-clock timeout stays TimeoutError. Holding the process to a resident-memory budget still belongs outside the process, for example in a cgroup.
or by execution time:
const fn = isolatedFunction(() => {
const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
await delay(duration)
return 'done'
}, { timeout: 50 })
await fn(100)
// => TimeoutError: Execution timed out
The timeout option enforces both a wall-clock limit (SIGKILL) and a CPU time limit (RLIMIT_CPU). A CPU-bound infinite loop will be terminated by the kernel via SIGXCPU:
const fn = isolatedFunction(() => {
while (true) { Math.random() }
}, { timeout: 5000 })
await fn()
// => CpuTimeError: CPU time limit exceeded
Logging
The logs are collected into a logging object returned after the execution:
const fn = isolatedFunction(() => {
console.log('console.log')
console.info('console.info')
console.debug('console.debug')
console.warn('console.warn')
console.error('console.error')
return 'done'
})
const { logging } = await fn()
console.log(logging)
// {
// log: ['console.log'],
// info: ['console.info'],
// debug: ['console.debug'],
// warn: ['console.warn'],
// error: ['console.error']
// }
Error handling
Any error during isolated-function execution will be propagated:
const fn = isolatedFunction(() => {
throw new TypeError('oh no!')
})
const result = await fn()
// TypeError: oh no!
You can also return the error instead of throwing it with { throwError: false }:
const fn = isolatedFunction(
() => {
throw new TypeError('oh no!')
},
{ throwError: false }
)
const { isFulfilled, value } = await fn()
if (!isFulfilled) {
console.error(value)
// TypeError: oh no!
}
API
isolatedFunction([options])
Creates an isolated-function instance. All functions created from the same instance share the same dependencies directory.
options
tmpdir
Type: string
Default: path.join(os.tmpdir(), 'isolated-fn-deps')
The directory used for installing code dependencies. Dependencies are installed once and reused across invocations, so only the first call that requires a given package pays the install cost.
const isolatedFunction = require('isolated-function')({
tmpdir: '/tmp/my-isolated-deps'
})
esbuild