Freestyle Docs

Freestyle / Guides

How to Run Node.js in a Sandbox

Bake Node.js into a VM snapshot, then run JavaScript snippets on one sandbox VM.

Build a snapshot with the Node.js runtime baked in, create one VM from it, then wrap it in a small runNode() helper that runs as many scripts as you like on that single sandbox.

Install the SDK

pnpm add freestyle@latest
bun add freestyle@latest
npm install freestyle@latest
yarn add freestyle@latest

Set your API key before calling the API:

export FREESTYLE_API_KEY="your-api-key"

Build a Snapshot with the Node.js Runtime

The base image is minimal, so install Node.js explicitly. Use nvm so the version is pinned and reproducible — install it into a fixed NVM_DIR, then install the Node version you want. The exec shell is a non-login sh, so set NVM_DIR and source nvm.sh in each command. Once the runtime is in place, snapshot the VM and delete the builder.

import { Freestyle } from "freestyle";

const freestyle = new Freestyle();

const { vm: builder } = await freestyle.vms.create({
  // Required: a VM reaches nothing it has not been allowed to.
  firewall: { rules: [{ action: "allow", source: {}, destination: { public: true } }] }, slug: "node-builder" });

// Install nvm into a fixed directory, then install Node 22 and make it the default.
await builder.exec(
  "export HOME=/root NVM_DIR=/opt/nvm && mkdir -p $NVM_DIR && " +
    "curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash",
);
await builder.exec(
  "export HOME=/root NVM_DIR=/opt/nvm && . $NVM_DIR/nvm.sh && nvm install 22 && nvm alias default 22",
);

// Source nvm so the right node is on PATH for every command below.
const node = "export NVM_DIR=/opt/nvm && . $NVM_DIR/nvm.sh &&";

// Confirm the runtime is present (nvm puts its node first on PATH).
console.log((await builder.exec(`${node} node -v`)).stdout?.trim()); // v22.22.3
console.log((await builder.exec(`${node} npm -v`)).stdout?.trim()); // 10.9.8

// Bake it into a reusable snapshot, then drop the builder.
const { snapshotId } = await builder.snapshot();
await builder.delete();

Every VM you create from snapshotId boots with Node.js ready, so you only pay the install cost once. This recipe is Ubuntu’s — on the 128 MiB freestyle/busybox image none of it applies, and Run It on BusyBox Instead builds the same snapshot there.

A Reusable runNode() Utility

The VM is your reusable sandbox: create it once, then run as many snippets as you like on it. Wrap that in a helper that takes the vm as its first argument, writes the script with vm.fs.writeTextFile, and runs it synchronously with vm.exec. Because Node was installed with nvm, the run command reuses the same node prefix so the right node is on PATH. vm.exec blocks until the program exits and hands you { stdout, stderr, statusCode }, so a single call captures the whole run.

async function runNode(vm, code: string) {
  const file = `/tmp/main-${crypto.randomUUID()}.mjs`;
  await vm.fs.writeTextFile(file, code);
  return await vm.exec(`${node} node ${file}`);
}

The helper never creates or deletes a VM — it just writes and runs. Each call writes to a unique /tmp/main-<uuid>.mjs path, so running many snippets on the same VM, sequentially or concurrently, can never overwrite each other’s script.

Create one VM and reuse it across every call:

const { vm } = await freestyle.vms.create({
  // Required: a VM reaches nothing it has not been allowed to.
  firewall: { rules: [{ action: "allow", source: {}, destination: { public: true } }] }, slug: "node-sandbox", snapshotId });

const sumResult = await runNode(
  vm,
  `const nums = [1, 2, 3, 4, 5];
const sum = nums.reduce((a, b) => a + b, 0);
console.log(\`node \${process.version}\`);
console.log(\`sum=\${sum}\`);`,
);

console.log(sumResult.statusCode); // 0
console.log(sumResult.stdout); // node v22.22.3\nsum=15

// Same VM, another snippet — no new machine needed.
const upperResult = await runNode(
  vm,
  `console.log("hello".toUpperCase());`,
);

console.log(upperResult.stdout.trim()); // HELLO

Pass Arguments and Throw on Failure

A raw { stdout, stderr, statusCode } is easy to misuse — it is simple to forget to check statusCode. Make the helper safe by default: take the same reused vm, accept an args array forwarded to process.argv, throw when the script exits non-zero, and return just the captured streams. Like runNode, it never touches the VM lifecycle.

async function runNodeStrict(vm, code: string, args: string[] = []) {
  const file = `/tmp/main-${crypto.randomUUID()}.mjs`;
  await vm.fs.writeTextFile(file, code);
  const argv = args
    .map((a) => `'${String(a).replace(/'/g, "'\\''")}'`)
    .join(" ");
  const result = await vm.exec(`${node} node ${file} ${argv}`);
  if (result.statusCode !== 0) {
    throw new Error(
      `node exited with status ${result.statusCode}: ${result.stderr ?? ""}`,
    );
  }
  return { stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
}

Pass the same vm you already created. The args are single-quoted before they reach the shell, so they arrive intact in process.argv.

const { stdout } = await runNodeStrict(
  vm,
  `const [a, b] = process.argv.slice(2).map(Number);
console.log(\`product=\${a * b}\`);`,
  ["6", "7"],
);
console.log(stdout); // product=42

// A failing script rejects instead of returning a bad result.
await runNodeStrict(vm, "process.exit(3);"); // throws: node exited with status 3

Run a Server

The same snapshot that runs one-off scripts can also host a long-lived HTTP server. A Freestyle snapshot is a full memory and disk capture, so it preserves a running service: stand the server up under systemd on a fresh VM from snapshotId, then route a domain to it and reach it from the public internet.

Create a separate VM from the same snapshot (a distinct server binding, and capture its vmId for routing):

const { vm: server, vmId } = await freestyle.vms.create({
  // Required: a VM reaches nothing it has not been allowed to.
  firewall: { rules: [{ action: "allow", source: {}, destination: { public: true } }] },
  slug: "node-server",
  snapshotId,
  idleTimeoutSeconds: null,
});

Write the server to /srv. It must bind 0.0.0.0 (not 127.0.0.1) so traffic routed in from outside the VM can reach it.

await server.fs.writeTextFile(
  "/srv/server.js",
  `const http = require("http");
const httpServer = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello from a Node.js server in a sandbox!\\n");
});
httpServer.listen(3000, "0.0.0.0", () => {
  console.log("listening on 0.0.0.0:3000");
});
`,
);

Run the server under systemd so it is supervised and restarts on crash. A systemd unit does not source your shell profile, so ExecStart must use the absolute node path, and any variables go through Environment=. Resolve that absolute path first:

const nodePath = (
  await server.exec(
    "export NVM_DIR=/opt/nvm && . $NVM_DIR/nvm.sh && command -v node",
  )
).stdout.trim(); // /opt/nvm/versions/node/v22.22.3/bin/node

await server.fs.writeTextFile(
  "/etc/systemd/system/nodeserver.service",
  `[Unit]
Description=Node HTTP server
After=network.target

[Service]
ExecStart=${nodePath} /srv/server.js
WorkingDirectory=/srv
Restart=always
Environment=HOME=/root

[Install]
WantedBy=multi-user.target
`,
);

await server.exec(
  "systemctl daemon-reload && systemctl enable --now nodeserver",
);

Wait until the server actually answers — poll for HTTP 200 on localhost:3000 so you know it is listening before you route traffic to it.

let ready = false;
for (let i = 0; i < 30 && !ready; i++) {
  const probe = await server.exec(
    "curl -s -o /dev/null -w '%{http_code}' http://localhost:3000 || true",
  );
  ready = probe.stdout?.trim() === "200";
  if (!ready) await new Promise((r) => setTimeout(r, 1000));
}
if (!ready) throw new Error("server did not become ready");

Route a domain to the VM’s port. Any unused subdomain of style.dev is yours to take, with no verification and no DNS records; to use a name you own, verify it and point its DNS at Freestyle first.

const domain = "my-app.style.dev"; // any unused style.dev subdomain
await freestyle.tls.rules.create({
  action: "allow",
  domain,
  source: { public: true },
  destination: { vmId, port: 3000 },
});

Fetch it from outside the VM:

const res = await fetch(`https://${domain}`);
console.log(res.status); // 200
console.log(await res.text()); // Hello from a Node.js server in a sandbox!

Snapshot this VM too and every machine you create from it boots with the server already listening on port 3000 — no startup step, just route a domain and go.

Stream the Server’s Logs

vm.exec() buffers a command and only returns once it finishes, so it can’t show a long-running service’s output as it happens. To watch the logs live, open a PTY on the VM — a real terminal streamed over a WebSocket (server-side only, Node 22+) — and follow the unit’s journal. onData delivers the bytes as they arrive:

const session = await server.pty.open({
  cols: 120,
  rows: 30,
  onData: (bytes) => process.stdout.write(bytes), // live log lines
});

// Follow the service; new lines stream in until you detach.
session.write("journalctl -u nodeserver -f\n");

// session.detach() drops your handle — the service keeps running in the VM.

Run It on BusyBox Instead

Everything above assumes freestyle/ubuntu. freestyle/busybox is a different machine: 1 vCPU, 128 MiB of memory, a 1 GB disk, and a sh-only userland with no package manager. nvm cannot run there, because it needs bash and curl and neither is installed. Two things stand between that image and a working Node, and each is one command.

The first is a missing library. The image ships glibc, libm, and libpthread — everything the Node binary asks for except libdl.so.2, and since glibc 2.34 that library’s contents live inside libc anyway. The second is headroom: with 128 MiB and no swap the kernel has nowhere to spill, so it answers any real allocation by killing the process. A swap file on the mostly-empty 1 GB disk fixes that, and it is the difference between a toy and a machine that behaves.

const { vm: builder } = await freestyle.vms.create({
  // Required: a VM reaches nothing it has not been allowed to.
  firewall: { rules: [{ action: "allow", source: {}, destination: { public: true } }] },
  slug: "node-busybox-builder",
  snapshotId: "freestyle/busybox",
});

await builder.exec(
  // glibc 2.34 folded libdl into libc; BusyBox omits the compatibility stub.
  "ln -sf /lib/libc.so.6 /lib/libdl.so.2 && " +
    // 256 MiB of swap, which costs a quarter of a disk nothing else is using.
    "dd if=/dev/zero of=/swapfile bs=1M count=256 && chmod 600 /swapfile && " +
    "mkswap /swapfile && swapon /swapfile",
);

256 MiB is a recommendation, not a requirement — count=256 is the whole knob if you want to trade disk for headroom.

Now the runtime. Use the glibc-217 build from unofficial-builds rather than the download nodejs.org offers. It is the same Node, built to run on distributions older than its own toolchain, which means libstdc++ and libgcc are linked into the binary instead of loaded from the system — the reason it needs nothing installed. Take the .tar.gz and not the .tar.xz: unpacking xz wants a 64 MiB dictionary, which is most of this VM’s memory, so unxz gets killed partway through. Pipe the download straight into tar and keep only bin/node. That one file is the whole runtime.

const version = "v22.23.2";
const tarball =
  `https://unofficial-builds.nodejs.org/download/release/${version}` +
  `/node-${version}-linux-x64-glibc-217.tar.gz`;

await builder.exec(
  `mkdir -p /opt/node && wget -qO- ${tarball} | ` +
    `tar -xz -C /opt/node --strip-components=2 node-${version}-linux-x64-glibc-217/bin/node && ` +
    "ln -sf /opt/node/node /bin/node",
);

console.log((await builder.exec("node -v")).stdout?.trim()); // v22.23.2

const { snapshotId } = await builder.snapshot();
await builder.delete();

That leaves a 131 MB binary and the swap file on a disk still half empty, and a VM that runs real work: node -e returns in 0.19s, a ten-million-element array builds instead of being killed, and eight scripts run concurrently in about five seconds. Push to a dozen at once and it thrashes rather than dies. Nothing here is stubbed out either — TLS fetch, crypto, zlib, child_process, worker_threads, and a full-ICU Intl all work on the base image as shipped.

The symlink into /bin is what pays off. node is on PATH for every exec, so nothing needs the ${node} prefix the nvm install required — runNode() and runNodeStrict() from the sections above work as written once you drop it:

async function runNode(vm, code: string) {
  const file = `/tmp/main-${crypto.randomUUID()}.mjs`;
  await vm.fs.writeTextFile(file, code);
  return await vm.exec(`node ${file}`);
}

/tmp is a tmpfs here, so it spends memory rather than disk. That is fine for a few KB of script; stage anything larger under /srv.

For dependencies rather than single-file scripts, widen the extraction to take the whole bin and lib — 149 MB instead of 131 MB, and npm lands beside node:

await builder.exec(
  `mkdir -p /opt/node && wget -qO- ${tarball} | ` +
    `tar -xz -C /opt/node --strip-components=1 ` +
    `node-${version}-linux-x64-glibc-217/bin node-${version}-linux-x64-glibc-217/lib && ` +
    "ln -sf /opt/node/bin/node /bin/node && ln -sf /opt/node/bin/npm /bin/npm",
);

npm install hono finishes in about 11 seconds this way. Without the swap file it does not finish at all.

Snapshots capture memory, so swapon survives into every VM you create from snapshotId, and across a pause and resume. Re-run it if you ever cold-boot the disk on its own.

Supervise a BusyBox Server Without systemd

There is no systemd on this image, so the unit file in Run a Server has nothing to read it. BusyBox ships runit instead: runsvdir watches a directory of services, each one a directory holding an executable run script, and restarts anything that exits. That is the entire supervisor. Write /srv/server.js exactly as above — it still has to bind 0.0.0.0 — and describe the service:

await server.fs.writeTextFile(
  "/etc/service/node-server/run",
  `#!/bin/sh
exec /bin/node /srv/server.js >>/var/log/node-server.log 2>&1
`,
);

// /var/log does not exist on the base image. Without it the redirect fails,
// the run script exits immediately, and runsv respawns it forever.
await server.exec(
  "mkdir -p /var/log && chmod +x /etc/service/node-server/run && " +
    "start-stop-daemon -S -b -x /bin/runsvdir -- /etc/service",
);

The readiness poll needs two changes. There is no curl, so use BusyBox’s wget; and there is no /etc/hosts, so localhost does not resolve — address 127.0.0.1 directly.

let ready = false;
for (let i = 0; i < 30 && !ready; i++) {
  const probe = await server.exec(
    "wget -qO /dev/null http://127.0.0.1:3000 && echo up || true",
  );
  ready = probe.stdout?.trim() === "up";
  if (!ready) await new Promise((r) => setTimeout(r, 1000));
}
if (!ready) throw new Error("server did not become ready");

From there the domain mapping is identical — freestyle.tls.rules.create does not care what is inside the VM. SVDIR=/etc/service sv status node-server reports on the service, and sv restart and sv down control it. Kill the process and runsv has it listening again within a second.

journalctl is gone along with systemd, but the run script is already appending to a file, so follow that in a PTY for the same live stream:

session.write("tail -f /var/log/node-server.log\n");

None of this locks you into 128 MiB. resize grows a BusyBox VM’s memory, vCPU, and disk to whatever the workload actually needs, it applies live to a running machine, and the swap file keeps doing its job alongside the extra memory.

esc