n8n Code Node: JavaScript and Python Basics

How the n8n Code node works: the item structure, both run modes, built-in variables, copyable JavaScript and Python transforms, and when to use a regular node.

Summarize this post with AI

A 21-minute read, or the key points in about 30 seconds, in the assistant you already use.

Opens in a new tab with the prompt filled in. Nothing passes through this site.

Most n8n Code node errors come down to one thing: the shape of what you return. n8n passes data between nodes as a list of items, each wrapped in a json object, and if your code hands back a bare string or an array in the wrong place, the node fails with "Code doesn't return items properly".

Once that shape clicks, the Code node gets simple. You read items in, change them, and send items out.

This guide covers the item structure, the two run modes, the built-in variables you'll actually use, copyable JavaScript and Python snippets for common transforms, and the cases where a regular node beats code. If you're still wiring up APIs, my n8n HTTP Request node guide pairs well with this one, because most Code nodes sit right after an API call.

Everything here comes from n8n's official docs. I haven't run timed tests for this post, and the snippets are written from those docs.

Editorial cover showing a code editor card in the middle of an n8n-style workflow, with item cards flowing in from the left and out to the right

What is the n8n Code node?

The Code node runs your own JavaScript or Python as a step in a workflow. You use it to transform data or add logic that the built-in nodes don't cover.

It replaced the older Function and Function Item nodes in n8n 0.198.0. If you find an old tutorial using those, the ideas carry over, but the variable names have changed.

There are two places to write code in n8n: the Code node and the expressions editor (the {{ }} fields inside other nodes). Expressions are for one value in one field. The Code node is for reshaping whole items or whole lists.

Here's what each language gets, per n8n's docs:

FeatureJavaScriptPython (native)
Built-in variablesFull set ($input, $json, $('Node') and more)Only _items (all-items mode) and _item (per-item mode)
Field accessitem.json.name or item.json["name"]item["json"]["name"] only
Libraries on n8n Cloudcrypto and moment onlyNo imports at all
Libraries self-hostedAllowlisted npm and Node.js built-insAllowlisted stdlib and pip packages
Debug outputconsole.log()print()

My take: use JavaScript unless you have a specific Python library you need on a self-hosted instance. JavaScript gets every built-in helper, and most community examples are in it.

How does n8n structure data between nodes?

All data passed between nodes is an array of objects. Each object is one item, and its data lives under a json key:

json
[
  { "json": { "name": "Asha", "email": "asha@example.com", "plan": "pro" } },
  { "json": { "name": "Ravi", "email": "ravi@example.com", "plan": "free" } }
]

Files ride along under a separate binary key, with base64 data plus optional mimeType, fileName and fileExtension fields.

Two details save a lot of confusion. First, nodes process each item on their own, so a Slack node that receives 20 items sends 20 messages. Second, since n8n 0.166.0 the Code node adds the json key and the outer array for you if you leave them out. Other nodes don't do that, which is why the shape matters.

Diagram of n8n items as a stack of cards, each card holding a json object and an optional binary file attachment
Every node passes a list of items. Each item keeps its data under json and any file under binary.

What's the difference between the two run modes?

The Mode dropdown decides how often your code runs. This is the setting people get wrong most often.

ModeRunsRead input withReturn
Run Once for All Items (default)One time, whatever the item count$input.all()An array of items
Run Once for Each ItemOnce per input item$input.item or $jsonOne item (an object)

Run Once for All Items is the right default for anything that looks across items: sorting, deduplicating, totals, grouping, or turning one item into many.

Run Once for Each Item suits simple per-row changes, like cleaning one field. It reads more cleanly, but anything that compares items with each other won't work in it.

If your output has a different number of items than your input, you want all-items mode.

Which built-in variables do you actually need?

n8n ships a long list of built-ins, but a handful cover almost every Code node. Type $ in the editor to see the full list with autocomplete.

VariableWhat it returns
$input.all()Every input item, as an array
$input.first() / $input.last()The first or last input item
$input.itemThe current item (per-item mode)
$jsonShorthand for the current item's json (per-item mode)
$('Node Name').all()Every output item of an earlier node
$('Node Name').first()The first output item of an earlier node
$('Node Name').itemThe earlier node's item that produced the current one
$('Node Name').isExecutedWhether that node has run in this execution

The $('Node Name') helpers are how you reach back past the previous node. For example, a Code node after an HTTP Request can still read the original form submission from your Webhook node. If you build webhook flows, my guide to n8n webhooks shows where those items come from.

How do you write your first Code node in JavaScript?

Add a Code node, leave Language on JavaScript and Mode on Run Once for All Items. Then replace the sample code with this:

js
// Add a lowercase email and a signup flag to every item
const items = $input.all();

for (const item of items) {
  item.json.email = (item.json.email || "").trim().toLowerCase();
  item.json.isPaid = item.json.plan !== "free";
}

return items;

Select Execute step and check the output panel. You should see the same number of items, each with the cleaned email and the new isPaid field.

The same change in Run Once for Each Item mode is shorter:

js
// Per-item mode: $json is the current item's data
$json.email = ($json.email || "").trim().toLowerCase();
$json.isPaid = $json.plan !== "free";

return $input.item;

Both work. The difference shows up as soon as you need to look at more than one item at a time.

What are the most common Code node transforms?

These are the patterns I'd keep in a snippets file. All of them use all-items mode.

Filter items by a condition

js
// Keep only paid users
return $input.all().filter(item => item.json.plan !== "free");

Pick and rename fields

js
// Return a clean, flat object per item
return $input.all().map(item => ({
  json: {
    fullName: item.json.name,
    email: item.json.email,
    signedUp: item.json.created_at
  }
}));

Split one item with a list into many items

APIs often return one item holding an array, like a results field. To work with each result on its own:

js
// One API response -> one item per result
const results = $input.first().json.results || [];
return results.map(r => ({ json: r }));

Combine many items into one

js
// Many items -> one summary item
const items = $input.all();
const total = items.reduce((sum, item) => sum + Number(item.json.amount || 0), 0);

return [{ json: { count: items.length, total } }];

Remove duplicates by a key

js
const seen = new Set();
return $input.all().filter(item => {
  const key = item.json.email;
  if (seen.has(key)) return false;
  seen.add(key);
  return true;
});
Diagram of four Code node transforms: filtering items, splitting one item into many, merging many items into one, and removing duplicates
Most Code nodes do one of four jobs: filter, split, combine or dedupe.

How do you keep item linking working?

Item linking is how n8n knows which input item produced which output item. It's what makes $('Node Name').item work in later nodes.

n8n handles this for you with a single item, and when your code edits items in place. Per n8n's docs, you need to set it yourself when you create new items and there's more than one input item. Add a pairedItem field with the index of the source item:

js
return $input.all().map((item, i) => ({
  json: { name: item.json.name, source: "crm" },
  pairedItem: i
}));

Skip this and a later node using $('Webhook').item can fail to find the matching item, or pick the wrong one. If you split one item into many, point every new item at that one source index.

How does Python work in the Code node?

n8n now runs Python natively through task runners. Native Python arrived in n8n 1.111.0 and is stable as of n8n 2. The older Pyodide version (Python compiled to WebAssembly) was removed in n8n 2.0, so old Python snippets may break.

Native Python has fewer helpers than JavaScript. You get _items in all-items mode and _item in per-item mode, and you must use bracket access:

python
# Run Once for All Items: clean emails, flag paid users
for item in _items:
    data = item["json"]
    data["email"] = (data.get("email") or "").strip().lower()
    data["is_paid"] = data.get("plan") != "free"

return _items

Dot access like item.json.email worked in Pyodide but not in native Python. That's the first thing to fix in an older workflow.

On n8n Cloud, Python can't import any library, not even from the standard library. Self-hosted, you can allowlist modules with the N8N_RUNNERS_STDLIB_ALLOW and N8N_RUNNERS_EXTERNAL_ALLOW settings in the runner config, as long as the runner image includes them.

Can the Code node use npm packages, HTTP calls or credentials?

Partly, and the limits are deliberate.

  • npm packages: on n8n Cloud you only get the crypto module and the moment package. Self-hosted, you can allowlist built-in modules with NODE_FUNCTION_ALLOW_BUILTIN and npm packages with NODE_FUNCTION_ALLOW_EXTERNAL, after installing them in your n8n or runner image.
  • import statements: not supported. Use require() instead, or you'll get "'import' and 'export' may only appear at the top level".
  • Credentials: Code nodes can't read n8n credentials by design. For authenticated API calls, use the HTTP Request node with a stored credential. My n8n credentials guide covers the setup.
  • Files and HTTP: n8n's docs point you to the Read/Write Files from Disk and HTTP Request nodes for these jobs rather than code.

If you self-host, n8n's docs are blunt about task runners: they're the only isolation layer between workflow code and your n8n instance. Without external mode, anyone who can edit a workflow could reach your database, encryption key and stored credentials. Internal mode is deprecated from n8n 3.0.

For a self-hosted setup I'd run n8n with Docker on a Hostinger KVM VPS and add the n8nio/runners sidecar container in external mode. My step-by-step guide to self-hosting n8n with Docker walks through the base install.

Diagram of a self-hosted n8n container sending Code node tasks to a separate task runner container that holds the JavaScript and Python runners
In external mode, workflow code runs in its own runner container, away from n8n's data and keys.

How do you debug a Code node?

Start small and look at the data at each step.

  • Log it: console.log() in JavaScript or print() in Python writes to your browser's developer console when you run the node from the editor.
  • Pin input data: run the earlier nodes once, then pin their output so you can rerun the Code node without hitting the API again.
  • Return early: return $input.all() at the top of your code to confirm what's coming in before you change anything.
  • Check for missing fields: an undefined value from one odd item is the usual cause of "Code doesn't return an object".

Here's what the common errors mean, from n8n's troubleshooting docs:

ErrorUsual causeFix
Code doesn't return items properlyReturned something other than an array of itemsReturn an array of objects with a json key
A 'json' property isn't an objectSet json to an array or a stringWrap the value: { json: { results: [...] } }
Code doesn't return an objectNothing returned, or undefinedAdd a return, check the field exists on every item
'import' and 'export' may only appear at the top levelUsed ES import syntaxSwitch to require()
Cannot find moduleModule not installed or not allowlistedInstall it and allowlist it (self-hosted only)
$getCredentials is not definedTried to read credentials in codeUse the HTTP Request node with a credential

For runtime failures in production, pair this with an error workflow. My n8n error handling guide shows how to set up retries and alerts.

When should you avoid the Code node?

Code is the most flexible node, and also the hardest one for someone else to read later. n8n's own docs recommend dedicated nodes for common transforms. Reach for these first:

You want toUse this node instead
Add, rename or remove fieldsEdit Fields (Set)
Keep only some itemsFilter
Split a list field into itemsSplit Out
Group items into one listAggregate
Totals, counts, pivot-style summariesSummarize
Drop repeated items, even across runsRemove Duplicates
Order or cap the item listSort and Limit
Call an APIHTTP Request

My rule of thumb: if two or more nodes would do it cleanly, skip the code. Use the Code node when the logic needs loops, several conditions, or a calculation no node offers, like scoring a lead from five fields. You'll find plenty of both styles in my 30 n8n workflow examples.

The Code node also fits well inside AI workflows. In an n8n AI agent, a short Code node is a clean way to trim an API response before the model sees it, which keeps prompts smaller.

Frequently asked questions

What does the Code node do in n8n?▾
It runs your own JavaScript or Python as a workflow step, so you can transform items or add logic that the built-in nodes don't cover. It replaced the Function and Function Item nodes in n8n 0.198.0.
Should I use Run Once for All Items or Run Once for Each Item?▾
Use Run Once for All Items (the default) for anything that compares or combines items, like sorting, deduplicating or totals, and whenever the item count changes. Use Run Once for Each Item for simple per-row edits.
Can I use Python in the n8n Code node?▾
Yes. Native Python runs through task runners from n8n 1.111.0 and is stable as of n8n 2, while the older Pyodide version was removed in n8n 2.0. Native Python only gets _items and _item, uses bracket access, and can't import libraries on n8n Cloud.
Can I use npm packages in the n8n Code node?▾
On n8n Cloud, only the crypto module and the moment package. On a self-hosted instance you can install packages and allowlist them with NODE_FUNCTION_ALLOW_BUILTIN and NODE_FUNCTION_ALLOW_EXTERNAL.
Why does my Code node say it doesn't return items properly?▾
Your code returned something other than an array of objects with a json key, such as a bare string or an array inside json. Return items shaped like [{ json: { ... } }].
Can the Code node access my n8n credentials?▾
No. Code nodes can't read credentials by design. Use the HTTP Request node with a stored credential for authenticated calls, as covered in my n8n credentials guide: /blog/n8n-credentials-guide

Wrapping up

The Code node is small once you know its contract: items in, items out, each one wrapped in json. Pick the mode by whether your logic looks across items, set pairedItem when you create new items, and keep credentials and API calls in the nodes built for them.

Start with one of the transforms above on real data, then swap it for a dedicated node wherever one does the same job.

Share