The Code node (JavaScript and Python)

n8n · Advanced · 12 min

A few lines of code can replace a tangle of nodes, but only if you know how items go in and out.

Sometimes the visual nodes get clumsy, such as complex calculations or unusual text parsing. The Code node runs a short program you write. It supports JavaScript and Python (two popular programming languages). If you don't code, AI assistants can draft snippets, but have someone review them before production use.

Two modes decide how often your code runs:

  • Run Once for All Items (default): your code gets every item at once ($input.all() in JavaScript) and returns a list of items.
  • Run Once for Each Item: your code runs per item and works on $json, the current item.

Whatever you return must be items: a list of objects, each with its fields under json. n8n adds the json wrapper if you forget it, but returning the right shape avoids surprises.

Python in n8n 2.x runs natively through task runners (separate helper processes that run code safely apart from n8n itself). It uses _items and _item instead of $input, and needs bracket access like item["json"]["price"]. The older Pyodide Python was removed in 2.0, so old Python snippets may need updating.

Limits:

  • The Code node can't make web requests or read files directly; use HTTP Request and file nodes.
  • Reading server environment variables is blocked by default in 2.x.
  • On Cloud, external libraries aren't available (JavaScript has crypto and moment); self-hosters can allow more.
  • Never put secrets in code; use credentials.

If the logic fits in Edit Fields or an expression, prefer that: others can read it without coding.

Example

// Mode: Run Once for All Items (JavaScript)
const out = [];
for (const item of $input.all()) {
  const { price, quantity } = item.json;
  out.push({ json: { ...item.json, total: price * quantity } });
}
return out; // one output item per input item, each with a new total field

Remember

  • Choose Run Once for All Items or Run Once for Each Item
  • Return a list of items with fields under json
  • In 2.x, Python runs natively via task runners; no direct HTTP, files or env access

Watch out for

  • Copying a 1.x Pyodide Python snippet that uses dot access; native Python needs item["json"]["field"].

Check yourself

  1. In "Run Once for All Items" mode, what should your code return?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.n8n.io/build/code-in-n8n/using-the-code-node