# Code Runner Sandbox — Run Python & JavaScript Code in the Cloud (`nexgensignal/code-runner-sandbox`) Actor

Run Python or Node.js code in an isolated cloud container from an API call, a schedule or an AI agent: pip/npm packages, data on stdin, one run per list item, parsed JSON, stdout/stderr, exit code, time limits and saved files. Part of NexGen Signal — data tools and official-source data products

- **URL**: https://apify.com/nexgensignal/code-runner-sandbox.md
- **Developed by:** [NexGen Signal](https://apify.com/nexgensignal) (community)
- **Categories:** AI, Automation, Developer tools
- **Stats:** 4 total users, 3 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $33.50 / 1,000 code runs

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## 🧪 Code Runner Sandbox — Run Python & JavaScript Code in the Cloud

**Run Python 3.12 or Node.js 22 code in an isolated cloud container** from an API call, a schedule, a webhook or an AI agent, and get back standard output, standard error, the exit code, the run time and your output **parsed as JSON** — one row per run.

Install **pip or npm packages** for the run, pass data on standard input, run the same code **once per item of a list** (up to 10,000 items, one row each), set environment variables, a time limit per run (1 second to an hour) and an output cap, and **save files your code writes** (CSV, images, reports) with download links.

Your code runs in its own folder, the process and anything it starts are stopped at the time limit, and the Apify token and other platform secrets are removed from the environment your code sees. The unit is one completed code run (a run that errors or times out is still a completed run).

### Who buys this and for what job

- **AI agents** that need to execute code they wrote and read the result.
- **No-code automations** (Make, Zapier, n8n) that need a step of real Python or JavaScript.
- **Data teams** running a transform over many inputs in parallel with your own logic.
- **Developers** testing snippets with packages without setting up a machine.

Buyers usually search for this as **"code runner"**, **"run Python in the cloud"** or **"code sandbox API"**.

### 📊 Sample Output

![Table of code runs: run index, status, exit code, duration and parsed result.](https://api.apify.com/v2/key-value-stores/IXCaMKjxSmUTLHhmq/records/code-runner-sandbox.png)

| run_index | status | exit_code | duration_ms | result |
|---|---|---|---|---|
| 0 | ok | 0 | 91 | {"n": 0, "sq": 0} |
| 1 | ok | 0 | 82 | {"n": 1, "sq": 1} |
| 2 | ok | 0 | 111 | {"n": 2, "sq": 4} |
| 3 | ok | 0 | 94 | {"n": 3, "sq": 9} |
| 4 | ok | 0 | 82 | {"n": 4, "sq": 16} |
| 5 | ok | 0 | 147 | {"n": 5, "sq": 25} |

Rows from live run `GQ4RfMKTle5Xld6ZG` on Apify (one Python snippet run once per item of a 40-item list). Notice each run gets its own row with its own parsed result, so a list job maps straight to a table.

### ✅ What you get

Every field of each record:

- `record_id`, `run_index`, `language` — the run and its position in your list.
- `status`, `exit_code`, `timed_out`, `duration_ms` — ok / error / timeout, exit code, run time.
- `result`, `result_parse_error` — stdout parsed as JSON (whole output or last line).
- `stdout`, `stderr`, `stdout_truncated`, `stderr_truncated` — the raw output, capped at maxOutputKb.
- `input` — the list item this run received.
- `files` — saved files: path, bytes, download URL.
- `packages`, `runtime_version`, `started_at`, `finished_at` — what ran, and when.

### ⚙️ Sample inputs

**Sum a list in Python (the Store example)**

```json
{
  "language": "python",
  "code": "import sys, json\n\n# Data arrives on standard input (and in the file named by $INPUT_FILE).\ndata = json.load(sys.stdin)\nvalues = data[\"values\"]\n\n# Print JSON; it comes back parsed in the \"result\" field.\nprint(json.dumps({\"sum\": sum(values), \"count\": len(values), \"mean\": sum(values) / len(values)}))\n",
  "stdin": "{\"values\": [3, 5, 8, 13]}"
}
```

Returns sum, count and mean in `result`.

**JavaScript with npm packages and a saved file**

```json
{
  "language": "javascript",
  "packages": ["lodash", "date-fns@3"],
  "code": "import _ from 'lodash';\nimport fs from 'fs';\nconst d = JSON.parse(fs.readFileSync(0, 'utf8'));\nfs.writeFileSync('out.csv', 'a,b\\n1,2\\n');\nconsole.log(JSON.stringify({ chunks: _.chunk(d.v, 2) }));",
  "stdin": "{\"v\": [1, 2, 3, 4, 5]}",
  "saveFiles": ["out.csv"]
}
```

**Run once per item**

```json
{
  "language": "python",
  "code": "import sys, json\nx = json.load(sys.stdin)\nprint(json.dumps({'n': x, 'square': x * x}))",
  "inputs": [1, 2, 3, 4, 5]
}
```

Five rows, five billed runs.

**pandas with a 5-minute limit**

```json
{
  "language": "python",
  "packages": ["pandas"],
  "code": "import pandas as pd, json, sys\ndf = pd.DataFrame(json.load(sys.stdin))\nprint(df.describe().to_json())",
  "stdin": "[{\"a\": 1, \"b\": 2}, {\"a\": 3, \"b\": 5}]",
  "timeoutSecs": 300
}
```

Input fields:

| Field | Meaning |
|---|---|
| `language`, `code` | python or javascript; your program (up to 500 KB). |
| `stdin`, `inputs` | data for one run, or a list to run once per item (each item as JSON on stdin and in $INPUT_FILE). |
| `packages` | pip or npm packages (up to 30), installed once per actor run. |
| `env` | environment variables for your code. |
| `timeoutSecs`, `maxOutputKb` | limit per run (default 60 s) and output cap (default 1 MB). |
| `parseJsonOutput` | parse stdout as JSON into `result` (default on). |
| `saveFiles` | relative paths or patterns of files to keep, with download links. |
| `maxRuns` | stop after this many runs (default 1,000). Each completed run is billed. |

### 🧾 JSON sample record

```json
{
  "record_id": "4116ea2d5b4fcbdceab3bf9f",
  "run_index": 0,
  "language": "javascript",
  "status": "ok",
  "exit_code": 0,
  "timed_out": false,
  "duration_ms": 129,
  "result": {
    "chunks": [
      [
        1,
        2
      ],
      [
        3,
        4
      ],
      [
        5
      ]
    ],
    "day": "2026-10-18",
    "token": null
  },
  "result_parse_error": null,
  "stdout": "{\"chunks\":[[1,2],[3,4],[5]],\"day\":\"2026-10-18\",\"token\":null}\n",
  "stderr": "",
  "stdout_truncated": false,
  "stderr_truncated": false,
  "input": null,
  "files": [
    {
      "path": "out/r.csv",
      "bytes": 8,
      "url": "https://api.apify.com/v2/key-value-stores/HwdQWiWdEuiGmW4HF/records/run0-91ce612978-r.csv"
    }
  ],
  "packages": [
    "lodash",
    "date-fns@3"
  ],
  "runtime_version": "Node.js v22.23.3",
  "started_at": "2026-10-18T02:50:35Z",
  "finished_at": "2026-10-18T02:50:35Z"
}
```

### 🔧 How it works

Packages are installed once at the start (pip into a private folder, npm into the run's folder); a package that cannot be installed stops the run with the installer's message and nothing charged. Each run then starts a fresh process in its own folder, writes your input to stdin and $INPUT_FILE, and collects output up to the cap. At the time limit the whole process group is killed. JavaScript that uses import/export or top-level await runs as an ES module; otherwise as CommonJS.

Your code can reach the internet (it is your run). The environment it sees has Apify's tokens and anything named like a token, secret, password or key removed, except variables you pass in `env`.

Each run's row is pushed and then charged. The run receipt (`RUN_RECEIPT`) has the install log, every run's status and time, files stored, and the delivered and charged counts (your code itself is not copied into the receipt).

### 💰 Pricing example

Per code run delivered, no start fee, no monthly charge:

| Apify plan | Price per code run |
|---|---|
| Free | $0.05 |
| Bronze | $0.045 |
| Silver | $0.04 |
| Gold, Platinum, Diamond | $0.0335 |

- 10 code runs: $0.50 on the Free plan, $0.34 on Gold.
- 1,000 code runs: $50.00 on the Free plan, $33.50 on Gold.
- 10,000 code runs: $500.00 on the Free plan, $335.00 on Gold.

**Coverage and size.** Proof runs on 18 Oct 2026: 40 list items through one Python snippet in 10 seconds; Node.js 22 with lodash and date-fns plus a saved CSV in 5 seconds (the Apify token was not visible to the code); a sleep past a 3-second limit was stopped at 3.0 seconds and reported as timeout; a package that does not exist stopped the run with pip's message and nothing charged. Default memory is 1 GB; give the run more memory for heavier code.

### ⚖️ Legal & ToS

You are responsible for the code you run and what it does. Do not use it to attack, scrape against a site's rules, or process data you have no right to.

The actor does not keep your code after the run; it is not copied into the dataset or the receipt.

### ❓ FAQ

**Which versions?**
Python 3.12 and Node.js 22.

**Is a failing run billed?**
Yes, a run that exits with an error or times out is a completed run (its stderr tells you why). A run stopped before it starts (bad package, invalid input) is not billed.

**Can my code use the network?**
Yes.

**How do I return data?**
Print JSON to stdout; it comes back parsed in `result`. Or write files and list them in saveFiles.

### 🆘 Troubleshooting

- **result is empty but stdout has text** — stdout was not JSON; see result_parse_error, or turn parseJsonOutput off.
- **status timeout** — Raise timeoutSecs (up to 3,600).
- **Invalid input: the packages could not be installed** — Check the package names and versions.

### 🔗 Related Actors

- [CMS & Hosting Detector](https://apify.com/nexgensignal/website-tech-stack-api) — what a website is built with
- [Website Performance Audit API](https://apify.com/nexgensignal/website-performance-audit-api) — Lighthouse scores and web vitals
- [Bulk Email Extractor from Domain List](https://apify.com/nexgensignal/bulk-website-contact-extractor) — contact details from website lists

🏢 **About NexGen Signal** — data tools and official-source data products. Browse the catalog: [apify.com/nexgensignal](https://apify.com/nexgensignal)

### ⭐ Found this useful?

If this actor saved you time, a rating on its Apify Store page helps other buyers find it.

Part of NexGen Signal — data tools and official-source data products.

# Actor input Schema

## `language` (type: `string`):

Python 3.12 or Node.js 22.

## `code` (type: `string`):

Your program, up to 500 KB. Read input from standard input or the file at $INPUT_FILE; print results to standard output (print JSON to get it parsed into 'result'). JavaScript with import/export or top-level await runs as an ES module.

## `stdin` (type: `string`):

Text passed to the program's standard input (and saved to $INPUT_FILE). Used for a single run.

## `inputs` (type: `array`):

A JSON list. The code runs once per item, with that item as JSON on standard input and in $INPUT_FILE. Each run is one row and one billed run. Up to 10,000 items.

## `packages` (type: `array`):

pip packages for Python (e.g. pandas, requests==2.32.3) or npm packages for JavaScript (e.g. lodash, date-fns@3). Installed once per run of this actor; up to 30.

## `env` (type: `object`):

NAME: value pairs your code can read. Shown only to your code; names are listed in the receipt, values are not.

## `timeoutSecs` (type: `integer`):

Each run is stopped after this many seconds (status 'timeout').

## `parseJsonOutput` (type: `boolean`):

Parse standard output (or its last line) as JSON into the 'result' field.

## `maxOutputKb` (type: `integer`):

Keep at most this much of stdout and of stderr per run.

## `saveFiles` (type: `array`):

Relative paths or patterns of files your code writes (e.g. out.csv, charts/\*.png). Each is stored and linked in the row; up to 50 MB per run.

## `maxRuns` (type: `integer`):

Stop after this many runs. Each completed run is billed, including runs that end in an error or timeout.

## Actor input object example

```json
{
  "language": "python",
  "code": "import sys, json\n\n# Data arrives on standard input (and in the file named by $INPUT_FILE).\ndata = json.load(sys.stdin)\nvalues = data[\"values\"]\n\n# Print JSON; it comes back parsed in the \"result\" field.\nprint(json.dumps({\"sum\": sum(values), \"count\": len(values), \"mean\": sum(values) / len(values)}))\n",
  "stdin": "{\"values\": [3, 5, 8, 13]}",
  "packages": [],
  "timeoutSecs": 60,
  "parseJsonOutput": true,
  "maxOutputKb": 1024,
  "saveFiles": [],
  "maxRuns": 1000
}
```

# Actor output Schema

## `results` (type: `string`):

The delivered (and billed) records.

## `receipt` (type: `string`):

Per-link outcome, robots result, delivered and charged counts.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "language": "python",
    "code": `import sys, json

# Data arrives on standard input (and in the file named by $INPUT_FILE).
data = json.load(sys.stdin)
values = data["values"]

# Print JSON; it comes back parsed in the "result" field.
print(json.dumps({"sum": sum(values), "count": len(values), "mean": sum(values) / len(values)}))`,
    "stdin": "{\"values\": [3, 5, 8, 13]}"
};

// Run the Actor and wait for it to finish
const run = await client.actor("nexgensignal/code-runner-sandbox").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "language": "python",
    "code": """import sys, json

# Data arrives on standard input (and in the file named by $INPUT_FILE).
data = json.load(sys.stdin)
values = data[\"values\"]

# Print JSON; it comes back parsed in the \"result\" field.
print(json.dumps({\"sum\": sum(values), \"count\": len(values), \"mean\": sum(values) / len(values)}))
""",
    "stdin": "{\"values\": [3, 5, 8, 13]}",
}

# Run the Actor and wait for it to finish
run = client.actor("nexgensignal/code-runner-sandbox").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "language": "python",
  "code": "import sys, json\\n\\n# Data arrives on standard input (and in the file named by $INPUT_FILE).\\ndata = json.load(sys.stdin)\\nvalues = data[\\"values\\"]\\n\\n# Print JSON; it comes back parsed in the \\"result\\" field.\\nprint(json.dumps({\\"sum\\": sum(values), \\"count\\": len(values), \\"mean\\": sum(values) / len(values)}))\\n",
  "stdin": "{\\"values\\": [3, 5, 8, 13]}"
}' |
apify call nexgensignal/code-runner-sandbox --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,nexgensignal/code-runner-sandbox"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/0MgfKsGAmX2fuoBge/builds/qz2ao7uI6HkhYxzwW/openapi.json
