Contents

n8n Code Node Tutorial: Process Data with JavaScript and Python

When expressions and built-in nodes can't handle what you need, the Code node lets you write JavaScript (or Python) directly.

Two execution modes

ModeNumber of executionsRead data withBest for
Run Once for All ItemsRuns once for the entire node$input.all()Aggregating, sorting, merging, and generating multiple new items
Run Once for Each ItemRuns once for each item$input.item / $jsonTransforming items one at a time

Return format

The Code node must return an items array, with each element in the form { json: {...} }:

return [
  { json: { name: "Alex", score: 90 } },
  { json: { name: "Sam", score: 85 } },
];

In Run Once for Each Item mode, you can return a single object:

return { json: { ...$json, total: $json.price * $json.qty } };

(Newer versions of n8n also accept a plain object and automatically wrap it as { json: ... }, but spelling it out makes mistakes less likely.)

Example: Calculate and add fields (run once per item)

const price = Number($json.price);
const qty = Number($json.qty);

return {
  json: {
    ...$json,
    subtotal: price * qty,
    shipping: price * qty >= 1000 ? 0 : 60,
  },
};

Example: Aggregate (run once for all items)

const items = $input.all();

const byRegion = {};
for (const item of items) {
  const { region, amount } = item.json;
  byRegion[region] = (byRegion[region] ?? 0) + Number(amount);
}

return Object.entries(byRegion)
  .sort((a, b) => b[1] - a[1])
  .map(([region, total]) => ({ json: { region, total } }));

With 100 input orders, the output contains one aggregated record per region.

Example: Generate multiple items

// Generate dates for the next 7 days
const days = [];
for (let i = 0; i < 7; i++) {
  days.push({ json: { date: $now.plus({ days: i }).toFormat("yyyy-MM-dd") } });
}
return days;

Example: Clean up complex API responses

const data = $input.first().json;

return data.results
  .filter((r) => r.status === "active")
  .map((r) => ({
    json: {
      id: r.id,
      name: r.profile?.display_name ?? r.username,
      email: r.contact?.email ?? null,
      tags: (r.tags ?? []).map((t) => t.label).join(", "),
    },
  }));

Read data from other nodes

As with expressions:

const settings = $("Get settings").first().json;
const orders = $("Orders").all();

Debugging

console.log($json);

The output appears in the browser's developer tools Console (when testing manually).

Use external npm packages

Self-hosted instances can allow the Code node to use built-in modules and external packages through environment variables:

NODE_FUNCTION_ALLOW_BUILTIN=crypto
NODE_FUNCTION_ALLOW_EXTERNAL=lodash,dayjs

External packages must be installed in the environment that runs the Code node (with Docker, this usually means creating a custom image). In n8n 2.x, the Code node runs in a task runner. See the task runners section of the official documentation for related settings.

Important changes in n8n 2.x

  • The Code node can't access environment variables ($env) by default, to prevent secret leaks.
  • $evaluateExpression() is no longer supported in the Code node.
  • Python: The old method that ran Python with Pyodide (browser-based Python) has been removed. The Python Code node in n8n 2.x requires a task runner running in "external mode" (the official n8nio/runners image is available), and its syntax differs from the old version.

Python example (requires a configured Python task runner)

# Run Once for All Items
results = []
for item in _items:
    data = item["json"]
    results.append({"json": {"name": data["name"].strip(), "length": len(data["name"])}})
return results

The new Python execution method uses _items (all items) or _item (per-item mode), and reads fields with dictionary bracket notation. It doesn't support _input or dot notation. If your environment doesn't have a Python task runner configured, use JavaScript.

When not to use the Code node

  • Simple value retrieval or formatting → use expressions
  • Splitting, merging, filtering, or sorting → use Split Out, Aggregate, Filter, or Sort
  • Calling an API → use HTTP Request

The fewer Code nodes you use, the easier it is for others to understand and maintain your workflow.

Updated October 12, 2026