सामग्री पर जाएँ

लेसन 9 · Data and Expressions

The Code Node: JavaScript and Python

Use the n8n Code node safely: choose a run mode, return correctly shaped items, keep item links, understand Python limits and know what the sandbox does not allow.

When a node chain becomes awkward, the Code node lets you write a script. It receives items, runs your code and returns items. It supports JavaScript and Python. Use it for clear, focused transformations, and keep it small enough that someone else can review it.

Two run modes

Mode When your code runs Use it for
Run Once for All Items (default) Once, seeing the whole list Totals, grouping, sorting, combining
Run Once for Each Item Once per item Independent per-record changes

JavaScript, all-items mode

JavaScript
// Read-only: paste into a Code node (Run Once for All Items)
const items = $input.all();

return items.map((item, index) => ({
  json: {
    ...item.json,
    fullName: `${item.json.first} ${item.json.last}`,
  },
  pairedItem: { item: index },
}));

Two details matter. First, return an array of items, each with its data under json. If the shape is wrong, the node reports an error. Second, pairedItem records which input item produced each output, so later expressions that use item linking keep working. This matters whenever you build new item objects.

In per-item mode you work with $input.item and return a single item:

JavaScript
// Read-only: Run Once for Each Item
const price = $input.item.json.price;
return { json: { ...$input.item.json, priceWithTax: price * 1.2 } };

Python

Current n8n versions run native Python through task runners. The earlier browser-style (Pyodide) Python was removed in 2.0. Native Python has important differences:

  • In all-items mode you use _items; in per-item mode, _item. Other n8n built-in helpers are not available.
  • Use bracket access, item["json"]["name"], not dot access.
  • Some unsafe built-ins are blocked. Importing libraries needs an allowlist on self-hosted instances, and n8n Cloud does not allow Python library imports.
Python
# Read-only: native Python Code node, all-items mode
return [
    {"json": {**item["json"], "fullName": f'{item["json"]["first"]} {item["json"]["last"]}'}}
    for item in _items
]

Older examples on the web may use different Python variable names. If code fails, compare it with the docs for your version.

What the Code node cannot do

The documentation says you cannot read or write the file system or make HTTP requests from the Code node; use the file nodes and the HTTP Request node instead. Since 2.0, access to environment variables from code is blocked by default. Do not try to work around these limits to read secrets. Use credentials for secrets.

For JavaScript, which npm packages you can import depends on your setup. Check the docs for your plan or server.

Test logic outside n8n

A good way to develop code is to write a function and test it with sample items. The stand-ins below are plain programs, so they run here.

JS Stand-in: build a summary item in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Python Stand-in: clean records in Python

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Writing code you can maintain

  • Handle empty input and missing fields.
  • Keep secrets out of the script; never paste an API key into code.
  • Add a short comment saying why the node exists.
  • Throw a clear error when data is invalid: throw new Error('Missing order ID') makes the failed execution explain itself.
  • Review any code an AI assistant writes before using it.

Common mistakes

  • Returning a plain object list without checking the required shape.
  • Dropping pairedItem and then wondering why .item expressions fail.
  • Expecting to call a web API from inside the Code node.

Keep your code node small

A Code node that grows to a hundred lines is hard to review, test and update. Consider these alternatives. Split it into several small nodes with clear names. Move shared logic into a sub-workflow. For heavy work, call your own small service through the HTTP Request node, where you can use version control and automated tests.

When you do keep code in the node, follow a short pattern: read the input, validate it, transform it and return items. Avoid changing input objects in place. Create new objects instead, which keeps the logic easy to follow and compare with the input. Test with an empty list, one item and many items. In per-item mode, do not assume anything about other items, because each run handles one record.

Practice

Write, on paper or in your own editor, a function that receives items with email and amount, and returns one item per distinct email with the total amount. Decide first what to do with an empty email, a negative amount and capital letters. Test with at least three inputs, including an empty list. Then ask whether the Summarize node could do the same job without code. If it can, after you lowercase the emails with Edit Fields, the node version is probably the better choice. This habit of comparing both options keeps workflows readable. When you do use code, paste your test inputs into a sticky note so that the next person can repeat your checks.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which mode suits calculating one total across all items?

    The all-items mode sees the whole list at once.
  2. 2. What should a Code node return for items?

    n8n expects item objects with json data.
  3. 3. How do you read a field in native Python?

    Native Python uses bracket access.
  4. 4. How should the Code node get an API key?

    Credentials keep secrets out of code, and environment access is blocked by default.

Summary

  • Choose all-items or per-item mode to match the job.
  • Return correctly shaped items and keep pairedItem links.
  • Native Python uses _items or _item and bracket access.
  • Use dedicated nodes for HTTP and files, and credentials for secrets.

Next: The HTTP Request Node

आपकी प्रगति इसी ब्राउज़र में सेव होती है। खाते की ज़रूरत नहीं है।