# JavaScript & TypeScript Code Runner - npm, Rows In/Out (`automa-flow/javascript-code-runner`) Actor

Run your JavaScript or TypeScript main() on rows from a Dataset, JSON or n8n in one API call, or a Node.js script on a schedule. npm packages from a field, lodash, cheerio and csv tools preinstalled, encrypted secrets as environment variables, rows back with per-item status.

- **URL**: https://apify.com/automa-flow/javascript-code-runner.md
- **Developed by:** [Vadim Bezrukov](https://apify.com/automa-flow) (community)
- **Categories:** Developer tools, Automation, Integrations
- **Features:** Limited permissions
- **Stats:** 12 total users, 10 monthly users, 96.4% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $4.00 / 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.

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

## JavaScript & TypeScript Code Runner - npm, Rows In/Out

Run your own JavaScript or TypeScript `main()` on rows in **one API call** and get rows back. Send the items of an n8n, Make or Zapier step as `rows`, or point `datasetId` at another Actor's Dataset; lodash, date-fns, cheerio, the csv tools and more are already installed, extra npm packages come from a `packages` field, API keys go in encrypted `secrets` that your code reads from `process.env`. Whatever `main` returns lands in the run's Dataset in your own shape, and a failure arrives as an explicit status row, never as an empty success.

Built for automation steps that need real Node.js with npm packages: an n8n Cloud Code node that cannot load an npm package, a Pipedream Node.js step that has to move before Pipedream Workflows shut down on 2027-03-31, an agent asked to "run this JavaScript with lodash", or a Node.js script that should run on a schedule without a server of its own.

Latest notes are in the [changelog](https://apify.com/automa-flow/javascript-code-runner/changelog).

### What the first run returns

The Console prefill sends three order rows and this code:

```js
import groupBy from 'lodash/groupBy.js';

export function main(rows, ctx) {
  const regions = groupBy(rows, (row) => row.region);
  return Object.entries(regions).map(([region, orders]) => ({
    region,
    orders: orders.length,
    total: orders.reduce((sum, row) => sum + row.price * row.qty, 0),
  }));
}
```

The default Dataset gets one row per region, and `RUN_SUMMARY` says `SUCCESS`:

```json
[
  {"region": "EU", "orders": 2, "total": 149},
  {"region": "US", "orders": 1, "total": 65}
]
```

That run costs about **$0.0043**: one `code-run` event ($0.004), which includes the first 30 GB-seconds of compute, plus the $0.0003 start event.

### n8n in one node

Add an **HTTP Request** node after the node that holds your orders:

- Method `POST`, URL `https://api.apify.com/v2/acts/automa-flow~javascript-code-runner/run-sync-get-dataset-items`
- Authentication: a Header Auth credential with `Authorization` = `Bearer <your Apify API token>`. Keep the token in the credential, never in the URL.
- Body (JSON), with the previous node's items as `rows`. This `main` buckets orders by ISO week with date-fns and lodash:

```json
{
  "code": "import { formatISO, startOfISOWeek } from 'date-fns';\nimport groupBy from 'lodash/groupBy.js';\nimport sumBy from 'lodash/sumBy.js';\n\nexport function main(rows) {\n  const weeks = groupBy(rows, (r) =>\n    formatISO(startOfISOWeek(new Date(r.created_at)), { representation: 'date' }));\n  return Object.entries(weeks).map(([week, orders]) => ({\n    week,\n    orders: orders.length,\n    revenue: sumBy(orders, 'amount'),\n  }));\n}\n",
  "rows": {{ JSON.stringify($input.all().map(item => item.json)) }}
}
```

The response is the list of rows `main` returned, for example `[{"week": "2026-11-02", "orders": 2, "revenue": 65.5}, {"week": "2026-11-09", "orders": 1, "revenue": 99}]`. Connect a **Google Sheets** node ("Append or update row") next and map `week`, `orders` and `revenue` to columns; Airtable, a database or an LLM step read the same items. The official Apify node for n8n works the same way: pick this Actor, paste the same input and read the run's Dataset items. Set `failRunOnError` to `true` if the workflow should stop on a code error.

### Run a Node.js script on a schedule

With no `rows` and no `datasetId`, `main` runs once as a script. Its settings go in `input`, its keys in `secrets`, and it returns rows, saves a file, or both:

```js
import axios from 'axios';
import { stringify } from 'csv-stringify/sync';

export async function main(rows, ctx) {
  const { data } = await axios.get(ctx.input.url, {
    headers: { Authorization: `Bearer ${process.env.API_KEY}` },
    timeout: 30_000,
  });
  ctx.saveFile('export.csv', stringify(data, { header: true }), 'text/csv');
  return data;
}
```

Save that input as a Task (with `input` set to `{"url": "..."}` and `API_KEY` in `secrets`) and put the Task on a schedule. Each tick is one run: the rows go to that run's Dataset and the file to its Key-Value Store as `files-export.csv`. A script may run up to 3,600 s (`timeoutSeconds`); start a long one asynchronously, because a synchronous API call waits at most 300 s. A daily 10-minute script at 1 GB costs about $0.10 a run.

### Why use it

- **Rows in, rows out, one call.** Inline `rows`, a Dataset (`datasetId`) or an Actor-to-Actor integration go in; the rows your code returns come out in your own columns, with no envelope to unwrap.
- **npm packages from a field.** lodash, date-fns, cheerio, zod, axios and 8 other common packages are preinstalled, so most runs install nothing. Add more with `packages`, one npm package per line.
- **TypeScript without a build step.** Set `language` to `typescript` and the same code runs with type annotations, interfaces and type aliases.
- **Secrets as environment variables.** Keys go in `secrets` (encrypted in the input), your code reads `process.env.API_KEY`, and the values are removed from logs, status rows and `RUN_SUMMARY`. The code text itself is never logged, only its SHA-256.
- **A status for every item.** In `eachItem` mode one bad row never stops the others; `RUN_SUMMARY` lists the input indexes to resend.
- **Bounded.** Code timeout, output row cap, row size cap, log cap and `maxTotalChargeUsd` all hold, so an agent or a schedule cannot run away with a bill.
- **Made to be called again.** Every n8n or Make execution, schedule tick or scraper run is one call with the same code and new rows, so the JavaScript step lives inside the workflow instead of on someone's laptop.

### Call modes

| `callMode` | Calls | Use it for |
| --- | --- | --- |
| `allItems` (default) | `main(rows, ctx)` once, with the array of all input rows | grouping, joins, reshaping, one summary |
| `eachItem` | `main(row, ctx)` once per input row | per-row parsing, scoring or API calls where one failure must not stop the rest |

The names follow n8n's "Run Once for All Items" and "Run Once for Each Item". Export `main` (or a default function); it may be `async`, may be a generator or async generator, and may ignore its parameters. With no `rows` and no `datasetId`, `main([], ctx)` runs once as a script and reads its settings from `ctx.input`.

`ctx` holds `ctx.input` (the `input` object), `ctx.callMode`, `ctx.itemIndex` (the row index in `eachItem` mode), `ctx.saveFile(name, data, contentType)` and `ctx.log(...)`. There is no `ctx.env`: `process.env` holds only your `secrets` and a few fixed variables.

When `main` returns (or its promise resolves), the process ends, even if a timer, interval or socket is still open. Await everything your code needs before returning. An unhandled promise rejection or an error thrown from a timer while a unit runs fails that unit with `CODE_ERROR`.

### Input

| Field | Default | Notes |
| --- | --- | --- |
| `code` | prefill | An ES module that exports `main`, up to 200,000 characters |
| `language` | `javascript` | `javascript` (runs as `.mjs`) or `typescript` (runs as `.mts`) |
| `callMode` | `allItems` | `allItems` or `eachItem` |
| `rows` | prefill | Up to 10,000 JSON objects. Use `rows` or `datasetId`, not both |
| `datasetId` | none | Dataset to read; in an integration use `{{resource.defaultDatasetId}}` |
| `datasetOffset` / `maxRows` | 0 / 10,000 | Range of Dataset rows, up to 100,000 per run |
| `fields` | all | Up to 50 top-level fields to read from each Dataset row |
| `input` | `{}` | Parameters your code reads as `ctx.input` |
| `packages` | empty | Extra npm packages, one per line, up to 30 lines |
| `secrets` | none | Up to 20 environment variables, encrypted |
| `timeoutSeconds` | 60 | 1-3,600 s for starting Node.js and running `main` |
| `installTimeoutSeconds` | 120 | 10-300 s for the npm install |
| `maxOutputRows` | 10,000 | 1-100,000; rows above it are dropped and counted |
| `maxRowBytes` | 1 MiB | 1 KiB to 4 MiB per returned row |
| `maxLogBytes` / `logUserOutput` | 256 KiB / on | How much `console` output reaches the run log |
| `statusRows` | `failures` | `failures`, `all` or `none` |
| `failRunOnError` | off | End the run FAILED when the status is not `SUCCESS` or `NO_ROWS` |
| `maxInputBytes` | 64 MiB | 1-256 MiB of input passed to `main` |

Run memory is 1,024 MB by default (1,024 to 4,096 MB), the run timeout 4,200 s. A synchronous API call (`run-sync-get-dataset-items`) waits at most 300 s, so start longer jobs asynchronously and read the Dataset when the run finishes.

A run started with a shorter timeout (for example `timeout` in the API call) keeps time for its rows, status rows and charges: the install and the code get what is left, and `RUN_SUMMARY.notes` says so. When too little time is left to start the code, the run ends `RUN_DEADLINE` without running or charging anything.

### Return value rules

| `main` returns | Rows written |
| --- | --- |
| `undefined` or `null` | none (`NO_ROWS`) |
| a plain object | one row |
| an array, a `Set`, a generator or an async generator of objects | those rows |

Values convert the same way every time: `Date` becomes ISO 8601 text in UTC (an invalid date becomes `null`); `NaN` and infinities become `null`; a `BigInt` becomes a string; a `Map` becomes an object and a `Set` an array; a `Buffer` becomes base64 text; a typed array becomes an array of numbers; an object with `toJSON()` is converted through it; a field whose value is `undefined` is left out (inside an array it becomes `null`). Anything else (a function, a symbol, a class instance without `toJSON`, a circular reference, nesting deeper than 64 levels, an array member that is not an object) fails that unit with `OUTPUT_INVALID` and names the JSON path of the first bad value, for example `$[3].price`. A row larger than `maxRowBytes` fails the same way. The key `_status` is reserved for status rows, so a returned row that has it is refused.

### Packages

Preinstalled for your code (Node.js 22.23.4, npm 10.9.9), resolved from `import` and `require`:

`axios` 1.21.0, `cheerio` 1.2.0, `csv-parse` 7.0.3, `csv-stringify` 6.9.0, `date-fns` 4.4.0, `dayjs` 1.11.23, `exceljs` 4.4.0, `fast-xml-parser` 5.11.2, `jsonpath-plus` 11.2.2, `lodash` 4.18.1, `papaparse` 5.7.0, `uuid` 14.0.3, `zod` 4.6.7.

`packages` takes one npm package per line: a name (`left-pad`), an exact version (`left-pad@1.3.0`), a range without spaces (`left-pad@^1.3.0`, `left-pad@~1.3`, `left-pad@1.x`, `left-pad@>=1.2`, `left-pad@1.x||2.x`), a tag (`left-pad@latest`) or a scoped name (`@scope/name@1.2.3`). Blank lines and `#` comments are fine. A line that a preinstalled version surely satisfies is skipped and reported in `RUN_SUMMARY.packages.skipped`; asking for another version of a preinstalled package installs it for that run, and your code then gets the version you asked for.

Both `import x from 'pkg'` and `require('pkg')` work: a global `require` is defined for the code, and `createRequire(import.meta.url)` works as usual. Import a package's subpath with its file name where the package needs one, as in `lodash/groupBy.js`.

Refused before anything is installed, with the line number: options (`--registry`, `-g` and any line starting with `-`), git, GitHub and other URLs, `file:`, `link:`, `workspace:` and `npm:` aliases, local paths and tarballs, and ranges with spaces (write `^1.2.0` or `1.x` instead of `>=1.2 <2`). Packages come from `https://registry.npmjs.org/` only; private registries and `.npmrc` files are not read. Install scripts never run (`--ignore-scripts`), so a package that needs one, such as a native build or a browser download (`bcrypt`, `canvas`, `better-sqlite3`, `puppeteer`), will not work. An install larger than 500 MiB on disk ends `PACKAGE_INSTALL_FAILED`. Pick packages you trust; a misspelled name can be someone else's package.

### TypeScript

With `language: "typescript"` the code runs as an `.mts` module through Node.js's built-in type stripping: type annotations, interfaces, type aliases, generics and `import type` work, and nothing is type-checked. Syntax that needs code generation is refused with a clear error: `enum`, `namespace` with code in it and constructor parameter properties. Import types with `import type { ... }`; a plain `import { SomeType }` of a type-only name fails at load. There is no `tsconfig.json`, no `tsc` and no bundler.

### Secrets

`secrets` is an object of environment variables, for example `{"API_KEY": "...", "SHEET_ID": "..."}`. Keys use `A-Z`, `0-9` and `_`, start with a letter and cannot start with `APIFY_`, `ACTOR_`, `NODE_`, `NPM_`, `LD_` or `UV_` or be `PATH`, `HOME`, `TZ`, `LANG` or `LC_ALL`. Values up to 8 KB. Before anything reaches the run log, a status row or `RUN_SUMMARY`, every secret value of 6 or more characters, and its URL-encoded and base64 forms, is replaced with `[REDACTED:<KEY>]`. Shorter values are left as they are. Rows and files your code returns are your data and are stored exactly as returned, so do not return a secret.

### Output rows and status rows

Your rows go to the default Dataset as returned. Status rows carry `_status` and sit in the same Dataset:

```json
{
  "_status": "CODE_ERROR",
  "_unit": "item",
  "_input_index": 2,
  "_error_type": "TypeError",
  "_error": "Cannot read properties of undefined (reading 'toFixed')",
  "_error_line": 2,
  "_stderr_tail": "TypeError: Cannot read properties of undefined (reading 'toFixed')\n    at main (file:///opt/usernode/work/jcr-9ff8c3b8030950fd/user_main.mjs:2:47)",
  "_rows_returned": 0,
  "_duration_ms": 1,
  "_finished_at": "2026-11-11T12:00:00Z",
  "_schema_version": 1
}
```

With `statusRows: failures` (the default) a status row is written for every failed unit, and one row when the run wrote no rows of its own, so a run never ends with an empty Dataset and no explanation. That includes FAILED runs: rejected input writes one `FAILED` row whose `_error_type` names the reason, such as `INVALID_INPUT`. `all` adds a row for every unit, `none` writes none. `_unit` is `call` for the single `allItems` call and `item` for one input row; `_input_index` is the row's position, and for Dataset input its absolute offset. The `results` view shows everything; the `status` view shows only the status columns. Apify views select columns and do not filter rows, so filter on `_status` in the next step when you need only one kind.

Statuses: `SUCCESS`, `NO_ROWS`, `CODE_ERROR`, `OUTPUT_INVALID`, `TIMEOUT`, `MEMORY_LIMIT`, `NOT_RUN` (an `eachItem` row that was never reached because the run stopped), plus the run-level `PACKAGE_INSTALL_FAILED`, `BUDGET_EXCEEDED`, `RUN_DEADLINE`, `INTERRUPTED`, `INPUT_UNAVAILABLE` and `FAILED`.

In `eachItem` mode, if the code process dies on a row (for example it runs out of memory), that row gets its status and a fresh process continues with the next row, once per run. A second crash marks the remaining rows `NOT_RUN`. Module-level state does not survive that restart.

### Files

`ctx.saveFile('report.xlsx', buffer, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')` stores a string, `Buffer`, `ArrayBuffer` or typed array in the run's Key-Value Store as `files-report.xlsx` and returns the key. Up to 10 files and 50 MiB per run; names use letters, digits, `.`, `_` and `-`. Over a limit, `saveFile` throws inside your code so you can see why. `RUN_SUMMARY.files` lists each key, size, SHA-256, content type and record URL.

### RUN_SUMMARY

Read it first. It holds the run `status`, `callMode`, `language`, `nodeVersion` and `npmVersion`, the input source and counts, Dataset paging (`datasetItemsTotal`, `nextDatasetOffset`), counts per item status, rows written and dropped by the cap, `packages` (requested, skipped, installed with versions, download bytes), install and execution seconds, `childRestarts`, billed GB-seconds, charged events, `billingStatus`, `codeSha256` and `codeBytes` (never the code), the first error with type, line and redacted message, `failedInputIndexes` (up to 1,000) to resend, and `nextAction`.

For a `PARTIAL` run, send only the rows whose indexes are in `failedInputIndexes` after fixing the code. When `nextDatasetOffset` is set, run again with that `datasetOffset` for the rest.

### Pricing

Platform usage is included in the prices: you pay only these events.

| Event | Price | When |
| --- | --- | --- |
| Actor start | $0.0003 per GB of memory | every run |
| `code-run` | $0.004 | once per run in which your code started and finished, including a code error, a timeout or a memory or output limit; includes the first 30 GB-seconds |
| `extra-gb-minute` | $0.015 | each started GB-minute of install plus execution time beyond the included 30 GB-seconds |
| `packages-installed` | $0.004 | once per run that installed at least one npm package that was not preinstalled |
| `result-rows-100` | $0.0015 | each started 100 returned rows beyond the first 100 of a run |
| `dataset-rows-1000` | $0.002 | each started 1,000 rows read from a Dataset (`datasetId`) beyond the first 1,000 of a run, only with a `code-run` |

Not charged: invalid or unreadable input, a failed install, a run that `maxTotalChargeUsd` or the run timeout stopped before the code started, an interrupted run, status rows, saved files, rows above `maxOutputRows` and rows sent inline in `rows`. A code error is charged like a success because the compute was used.

| Example | Bill |
| --- | --- |
| The prefill (three rows, lodash, 1 GB) | about $0.0043 |
| An n8n workflow calling it 30 times a day with 500 rows back and a 5 s step | about $0.31 a day ($0.0103 a call) |
| A summary of a 20,000-row scraper Dataset in a few seconds | about $0.042 (19 x $0.002 for the rows read) |
| A daily 3-minute job at 2 GB (360 GB-seconds) | about $0.095 |
| A 20-minute script at 1 GB (1,200 GB-seconds) | about $0.30 |
| 20,000 returned rows in one run | adds 199 x $0.0015 = $0.30 |

Every run pays at least one `code-run`. For a sub-second snippet with no packages and no rows, a runner that charges per second of execution costs less; this one charges per run with 30 GB-seconds included, so it pays off when the step uses packages, rows or several seconds of work.

`maxTotalChargeUsd` is respected before the code starts: the Actor computes the largest bill the run could reach, shrinks the code timeout, then the Dataset rows it reads (with `nextDatasetOffset` for the rest) and then the row cap to fit, and says so in `RUN_SUMMARY.notes`. If even one `code-run` does not fit, the run ends `BUDGET_EXCEEDED` without running anything.

### Failure semantics

A problem in your code is an outcome, not a failed run: the run ends SUCCEEDED with status rows and a `RUN_SUMMARY` that names the error. The run itself fails only when the Actor cannot do its job: the input is invalid (including a refused `packages` line or a Dataset id that sits only inside an integration payload), the input Dataset cannot be read (`INPUT_UNAVAILABLE`, nothing charged, never treated as an empty input), storage cannot be written, a charge did not finish cleanly, or the image is broken. An empty Dataset is not a failure: `allItems` calls `main([], ctx)` and `eachItem` ends `NO_ROWS` without a charge.

`failRunOnError: true` makes the run end FAILED after the rows and `RUN_SUMMARY` are stored whenever the status is not `SUCCESS` or `NO_ROWS`, which is what an n8n HTTP Request node or a Make module needs to stop the scenario.

If the platform restarts a run while your code is running, the code is not run again (it may already have sent an email or written to an API): the run ends `INTERRUPTED`, rows already written stay, and nothing more is charged. Start a new run for the rest. A failed install is never retried, and your code is never retried except the single fresh process after a crash in `eachItem` mode, which continues with the next row and never repeats the row that crashed.

### Security model and its limits

Your code runs as a separate unprivileged user in its own process with a fresh environment: the run's Apify token and proxy password are not in that environment and the process cannot read the Actor's memory or environment. The JavaScript heap is capped at run memory minus 384 MiB, and the code is stopped with `MEMORY_LIMIT` when all its processes together use more than run memory minus 256 MiB. Limits on processes and threads (128 together; Node.js itself uses about ten), open files (512), file size (1 GiB) and CPU time hold, and at the timeout every process the code started is stopped, including ones that detached. The Actor's own runtime and the runner are read-only to your code. npm installs go into the run's own work directory, never into the Actor's runtime.

This is not a virtual machine. The code and the installer have outbound network access, because calling APIs is a core use; nothing isolates that traffic. You are responsible for the code you run, the services it contacts and the packages you install. Do not run code you have not reviewed. Your rows are never logged and never sent anywhere except this run's Dataset; your `console` output is logged when `logUserOutput` is on, redacted and capped.

### Moving a Pipedream Node.js step

| Pipedream | Here |
| --- | --- |
| `export default defineComponent({ async run({ steps, $ }) { ... } })` | `export async function main(rows, ctx) { ... }` |
| `steps.trigger.event` and earlier step exports | `rows` (the items you send) and `ctx.input` (fixed parameters) |
| `return value` / `$.export` | the value `main` returns becomes the rows |
| environment variables | `secrets`, read from `process.env` |
| npm packages imported at the top | preinstalled, or one line each in `packages` |

### API, Make, integrations and MCP

- **API:** `POST https://api.apify.com/v2/acts/automa-flow~javascript-code-runner/run-sync-get-dataset-items` returns the rows directly (up to 300 s); `POST .../runs` starts an asynchronous run. Send the token in the `Authorization: Bearer` header.
- **Make:** an HTTP "Make a request" module with the same URL, method and JSON body, and the token in a header.
- **After a scraper:** on the scraper's Integrations tab, connect this Actor (or a saved Task of it) and set `datasetId` to `{{resource.defaultDatasetId}}`, so your code runs over each new Dataset. A dataset id that sits only inside the integration's `payload` is not read; the run fails and says so.
- **Schedules:** save a Task with your code and `input` parameters (for example a date window) and put it on a schedule.

Agents can find the Actor through Apify MCP search; running it uses your Apify account, and `timeoutSeconds`, `maxOutputRows` and `maxTotalChargeUsd` bound each call. `RUN_SUMMARY` gives an agent the outcome without reading every row. For example, ask an agent: "Use automa-flow/javascript-code-runner to group these 200 order rows by customer with lodash, return the totals and stop at $0.05." It sends the rows and the code, then reads the status and the grouped rows back.

Direct MCP endpoint:

```
https://mcp.apify.com?tools=automa-flow/javascript-code-runner
```

If a run fails or looks wrong, open an Issue and include the run URL. Apify shares that run with us automatically, so there is no need to paste your code, data or keys.

### Technical details

- Node.js 22.23.4 and npm 10.9.9 inside `apify/actor-python:3.12`; the Actor's own runtime is Python, your code runs in a separate Node.js process.
- The code runs from a fresh `user_main.mjs` (or `user_main.mts`) in its own work directory, so stack traces point at your own line numbers. That directory's `package.json` sets `"type": "module"`.
- Inline rows are spooled to a file the code cannot read, then streamed to the code process; Dataset rows are read page by page, empty rows keep their place, and the read stops at `maxInputBytes` with a next offset.

# Changelog

This Actor's version history is a separate document: https://apify.com/automa-flow/javascript-code-runner/changelog.md

# Actor input Schema

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

An ES module on Node.js 22. Export main, sync or async: main(rows, ctx) in allItems mode, main(row, ctx) in eachItem mode. Return an object, an array of objects, an async iterable or nothing. Use import or require for packages. Keep API keys out of the code: put them in Secrets.

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

javascript runs the code as an .mjs module. typescript runs it as an .mts module with Node.js built-in type stripping: type annotations and interfaces work, enums and namespaces do not, and types are not checked.

## `callMode` (type: `string`):

allItems calls main(rows, ctx) once with all input rows (Run Once for All Items). eachItem calls main(row, ctx) once per row, and one failing row does not stop the others (Run Once for Each Item).

## `rows` (type: `array`):

Up to 10,000 JSON objects passed to main, for example the items of the previous n8n or Make step. Use rows or a Dataset, not both. The sample rows are dropped when a Dataset is picked.

## `datasetId` (type: `string`):

Apify Dataset whose rows are passed to main instead of rows. The run gets read access to this Dataset only. In an integration, set it to {{resource.defaultDatasetId}}.

## `datasetOffset` (type: `integer`):

First Dataset row to read (0-based). RUN_SUMMARY gives nextDatasetOffset when more rows remain.

## `maxRows` (type: `integer`):

How many Dataset rows to read in this run (1-100,000). Default 10,000. Rows beyond the first 1,000 cost $0.002 per started 1,000.

## `fields` (type: `array`):

Optional top-level field names to read from each Dataset row (up to 50). Leave empty for whole rows; fewer fields use less memory.

## `input` (type: `object`):

Any JSON object your code reads as ctx.input, such as a threshold or a date. With no rows and no Dataset, main(\[], ctx) runs as a script.

## `packages` (type: `string`):

Extra npm packages, one per line: a name, name@1.2.3, name@^1.2.0 or name@latest, scoped names allowed. Up to 30 lines. From the npm registry only, with install scripts off: git, GitHub, URLs, tarballs, file:, npm: aliases and options are refused. lodash, date-fns, dayjs, cheerio, zod, axios, csv and Excel tools are already installed.

## `secrets` (type: `object`):

Up to 20 values your code reads from process.env, for example {"API_KEY": "..."}. Stored encrypted and removed from logs, status rows and RUN_SUMMARY. Keys use A-Z, 0-9 and \_ and cannot start with APIFY\_, ACTOR\_, NODE\_, NPM\_, LD\_ or UV\_.

## `timeoutSeconds` (type: `integer`):

Wall time for starting Node.js and running main (all rows in eachItem mode), 1-3,600. A synchronous API call waits at most 300 s, so start longer jobs asynchronously. A run timeout shorter than this shortens it, with a note in RUN_SUMMARY.

## `installTimeoutSeconds` (type: `integer`):

Wall time for installing the npm packages, 10-300.

## `maxOutputRows` (type: `integer`):

Rows written to the Dataset at most (1-100,000). Rows above it are dropped and counted, and the run ends OUTPUT_LIMIT.

## `maxRowBytes` (type: `integer`):

Largest returned row as JSON, 1,024 to 4,194,304 bytes. A larger row fails its unit with OUTPUT_INVALID.

## `maxLogBytes` (type: `integer`):

How much of your code's console output (stdout and stderr) is logged, 0 to 1,048,576 bytes. Secret values are redacted.

## `logUserOutput` (type: `boolean`):

Write your code's console output to the run log (redacted and capped).

## `statusRows` (type: `string`):

failures writes a \_status row only for a failed or empty unit, all writes one per unit, none writes none (RUN_SUMMARY still has every count).

## `failRunOnError` (type: `boolean`):

When on, the run ends FAILED after storing rows and RUN_SUMMARY if the status is not SUCCESS or NO_ROWS, so an n8n or Make step stops on a code error.

## `maxInputBytes` (type: `integer`):

Largest input passed to main, as JSON lines, 1 MiB to 256 MiB. A Dataset read stops at this size and RUN_SUMMARY gives the next offset.

## `resource` (type: `object`):

Present on some webhook bodies. A dataset id here is not read: set datasetId to {{resource.defaultDatasetId}}.

## `payload` (type: `object`):

Added by Actor-to-Actor integrations. A nested dataset id is not read: set datasetId to {{resource.defaultDatasetId}}.

## Actor input object example

```json
{
  "code": "import groupBy from 'lodash/groupBy.js';\n\nexport function main(rows, ctx) {\n  const regions = groupBy(rows, (row) => row.region);\n  return Object.entries(regions).map(([region, orders]) => ({\n    region,\n    orders: orders.length,\n    total: orders.reduce((sum, row) => sum + row.price * row.qty, 0),\n  }));\n}\n",
  "language": "javascript",
  "callMode": "allItems",
  "rows": [
    {
      "order": "A-1",
      "region": "EU",
      "price": 12.5,
      "qty": 4
    },
    {
      "order": "B-2",
      "region": "US",
      "price": 3.25,
      "qty": 20
    },
    {
      "order": "C-3",
      "region": "EU",
      "price": 99,
      "qty": 1
    }
  ],
  "datasetOffset": 0,
  "maxRows": 10000,
  "input": {},
  "timeoutSeconds": 60,
  "installTimeoutSeconds": 120,
  "maxOutputRows": 10000,
  "maxRowBytes": 1048576,
  "maxLogBytes": 262144,
  "logUserOutput": true,
  "statusRows": "failures",
  "failRunOnError": false,
  "maxInputBytes": 67108864
}
```

# Actor output Schema

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

No description

## `runSummary` (type: `string`):

No description

## `billingReceipt` (type: `string`):

No description

# 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 = {
    "code": `import groupBy from 'lodash/groupBy.js';

export function main(rows, ctx) {
  const regions = groupBy(rows, (row) => row.region);
  return Object.entries(regions).map(([region, orders]) => ({
    region,
    orders: orders.length,
    total: orders.reduce((sum, row) => sum + row.price * row.qty, 0),
  }));
}`,
    "callMode": "allItems",
    "rows": [
        {
            "order": "A-1",
            "region": "EU",
            "price": 12.5,
            "qty": 4
        },
        {
            "order": "B-2",
            "region": "US",
            "price": 3.25,
            "qty": 20
        },
        {
            "order": "C-3",
            "region": "EU",
            "price": 99,
            "qty": 1
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("automa-flow/javascript-code-runner").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 = {
    "code": """import groupBy from 'lodash/groupBy.js';

export function main(rows, ctx) {
  const regions = groupBy(rows, (row) => row.region);
  return Object.entries(regions).map(([region, orders]) => ({
    region,
    orders: orders.length,
    total: orders.reduce((sum, row) => sum + row.price * row.qty, 0),
  }));
}
""",
    "callMode": "allItems",
    "rows": [
        {
            "order": "A-1",
            "region": "EU",
            "price": 12.5,
            "qty": 4,
        },
        {
            "order": "B-2",
            "region": "US",
            "price": 3.25,
            "qty": 20,
        },
        {
            "order": "C-3",
            "region": "EU",
            "price": 99,
            "qty": 1,
        },
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("automa-flow/javascript-code-runner").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 '{
  "code": "import groupBy from '\''lodash/groupBy.js'\'';\\n\\nexport function main(rows, ctx) {\\n  const regions = groupBy(rows, (row) => row.region);\\n  return Object.entries(regions).map(([region, orders]) => ({\\n    region,\\n    orders: orders.length,\\n    total: orders.reduce((sum, row) => sum + row.price * row.qty, 0),\\n  }));\\n}\\n",
  "callMode": "allItems",
  "rows": [
    {
      "order": "A-1",
      "region": "EU",
      "price": 12.5,
      "qty": 4
    },
    {
      "order": "B-2",
      "region": "US",
      "price": 3.25,
      "qty": 20
    },
    {
      "order": "C-3",
      "region": "EU",
      "price": 99,
      "qty": 1
    }
  ]
}' |
apify call automa-flow/javascript-code-runner --silent --output-dataset

```

## MCP server setup

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

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/1GFLB3lEf4WDfscYp/builds/f1Hk8jGAyHLUnosCM/openapi.json
