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

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

Pricing

from $4.00 / 1,000 code runs

Go to Apify Store
JavaScript & TypeScript Code Runner - npm, Rows In/Out

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

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.

Pricing

from $4.00 / 1,000 code runs

Rating

0.0

(0)

Developer

Vadim Bezrukov

Vadim Bezrukov

Maintained by Community

Actor stats

0

Bookmarked

12

Total users

10

Monthly active users

9 days ago

Last modified

Features

Limited permissions

Share

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.

What the first run returns

The Console prefill sends three order rows and this 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),
}));
}

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

[
{"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:
{
"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:

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

callModeCallsUse it for
allItems (default)main(rows, ctx) once, with the array of all input rowsgrouping, joins, reshaping, one summary
eachItemmain(row, ctx) once per input rowper-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

FieldDefaultNotes
codeprefillAn ES module that exports main, up to 200,000 characters
languagejavascriptjavascript (runs as .mjs) or typescript (runs as .mts)
callModeallItemsallItems or eachItem
rowsprefillUp to 10,000 JSON objects. Use rows or datasetId, not both
datasetIdnoneDataset to read; in an integration use {{resource.defaultDatasetId}}
datasetOffset / maxRows0 / 10,000Range of Dataset rows, up to 100,000 per run
fieldsallUp to 50 top-level fields to read from each Dataset row
input{}Parameters your code reads as ctx.input
packagesemptyExtra npm packages, one per line, up to 30 lines
secretsnoneUp to 20 environment variables, encrypted
timeoutSeconds601-3,600 s for starting Node.js and running main
installTimeoutSeconds12010-300 s for the npm install
maxOutputRows10,0001-100,000; rows above it are dropped and counted
maxRowBytes1 MiB1 KiB to 4 MiB per returned row
maxLogBytes / logUserOutput256 KiB / onHow much console output reaches the run log
statusRowsfailuresfailures, all or none
failRunOnErroroffEnd the run FAILED when the status is not SUCCESS or NO_ROWS
maxInputBytes64 MiB1-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 returnsRows written
undefined or nullnone (NO_ROWS)
a plain objectone row
an array, a Set, a generator or an async generator of objectsthose 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:

{
"_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.

EventPriceWhen
Actor start$0.0003 per GB of memoryevery run
code-run$0.004once 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.015each started GB-minute of install plus execution time beyond the included 30 GB-seconds
packages-installed$0.004once per run that installed at least one npm package that was not preinstalled
result-rows-100$0.0015each started 100 returned rows beyond the first 100 of a run
dataset-rows-1000$0.002each 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.

ExampleBill
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 stepabout $0.31 a day ($0.0103 a call)
A summary of a 20,000-row scraper Dataset in a few secondsabout $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 runadds 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

PipedreamHere
export default defineComponent({ async run({ steps, $ }) { ... } })export async function main(rows, ctx) { ... }
steps.trigger.event and earlier step exportsrows (the items you send) and ctx.input (fixed parameters)
return value / $.exportthe value main returns becomes the rows
environment variablessecrets, read from process.env
npm packages imported at the toppreinstalled, 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.