n8n Code Node: JavaScript & Python Transformation Examples

Affiliate/Ads disclaimer: Some links on this blog are affiliate/ads links to support this project going on, meaning I may earn a commission at no extra cost to you.


Published: April 24, 2026
Updated: May 7, 2026
n8n Code Node: JavaScript & Python Transformation Examples
⚡ n8n Workflow Automation T3 · Code Node
n8n Code Node: JavaScript & Python Transformation Examples

The Code node (n8n-nodes-base.code) executes custom JavaScript or Python as a workflow step, providing full access to incoming data for manipulation by adding, removing, or updating items. It has replaced the legacy Function and Function Item nodes since version 0.198.0. JavaScript runs natively on Node.js 18, while Python runs via the Pyodide WebAssembly runtime (legacy) or a native Python process through task runners. The node supports two execution modes: “Run Once for All Items” where code executes once for all inputs, and “Run Once for Each Item” where code runs individually per item. [1] [2] [3]

Property JavaScript Python (Legacy Pyodide)
Runtime Node.js 18 Pyodide (CPython via WebAssembly)
Available in Cloud ✅ Yes ⚠️ Limited – no external libraries
External Modules Self-hosted: npm via NODE_FUNCTION_ALLOW_EXTERNAL Pre-installed Pyodide packages only
Performance Fast – no extra compilation Slower – WebAssembly compilation overhead
async/await ✅ Yes ❌ Not supported in Pyodide
Console Output console.log() print()
Standard Libraries Full Node.js 18 stdlib Limited to Pyodide v0.25.0 built-in set
Version Introduced 0.1.0 1.0.0 (Pyodide); enhanced in 1.65.0

How do the two n8n Code node execution modes process workflow data?

The Code node offers two execution modes: “Run Once for All Items” which executes code once regardless of how many input items there are, and “Run Once for Each Item” which runs the code separately for each input item. To access all items at once use $input.all(); for processing individual items use $input.item.json. [1]

The “Run Once for All Items” mode is ideal for aggregation tasks like computing an average or counting records; the “Run Once for Each Item” mode excels at transforming each record independently. The community testing has found that Code nodes performing filtering or mapping typically take 1–3 seconds to execute [4]. For more patterns, refer to the core n8n nodes guide.

How do you transform JSON data with JavaScript in the n8n Code node?

JavaScript code within the Code node receives all input items via the $input.all() method and must return an array of objects, each containing a json key. A common example loops over every item to add a new field: for (const item of $input.all()) { item.json.myNewField = 1; } return $input.all();. [5]

To extract an array buried inside a JSON wrapper and transform it into n8n’s item structure, use mapping: return $input.first().json.data.map(item => ({ json: item })) [6]. For data aggregation workflows, n8n courses demonstrate Code nodes that calculate total revenue across all orders: you access the entire list at once, apply array methods like .reduce(), and return a single summary item. For more advanced data processing strategies, see the ETL pipeline guide.

How do you write Python code in the n8n Code node for data transformation?

Python in the Code node (legacy Pyodide mode) accesses items through the _input.all() variable; return the transformed list with return _input.all(). Python list comprehension enables compact field extraction: summaries = [item.json.get("summary") for item in _input.all()]; return [{"merged_summary": " ".join(summaries)}]. [1]

Important distinctions: Python code should avoid using syntax not supported by the runtime; for example, libraries beyond Pyodide’s built-in set are unavailable on n8n Cloud. The Code node takes longer to process Python than JavaScript due to extra compilation steps. For structured Python data, the add_column helper method appends a new field to a DataFrame, enabling data-science patterns directly within n8n without external libraries. [1] For more on Python usage, see the n8n security hub.

How do $json, $input, and the item data model work inside the Code node?

In n8n, all data passed between nodes is an array of objects, each containing a json key. Inside the Code node, $json is shorthand for $input.item.json (available only in “Each Item” mode), while $input.all() retrieves the entire array of all input items regardless of mode. [1]

Each item also contains optional binary, pairedItem, and index properties. The Code node returns the modified items by simply executing a return statement on the items: the return items pattern is the standard exit point for JavaScript, while Python uses return _input.all(). Failure to correctly structure the returned array—for example, setting json to an array instead of an object—produces the error “A ‘json’ property isn’t an object” [7]. For branching on conditions, combine the Code node with IF & Switch nodes.

⚠️ Data Structure Gotcha: Starting from n8n 0.166.0, the Code node automatically adds the json key if missing and wraps items in an array if needed. However, for maximum compatibility, always explicitly return an array of objects with the json property: return [{ json: { key: "value" } }] [7].

How can you handle dates and import external modules in the Code node?

In JavaScript mode, n8n provides the Luxon library globally for date operations—access it with DateTime without requiring any import statement. In Python, use from datetime import datetime (available since Pyodide includes datetime) and call datetime.fromtimestamp() for conversions. [8]

Self-hosted users can enable external npm modules by setting the environment variables NODE_FUNCTION_ALLOW_BUILTIN=* for Node.js built-in modules (such as crypto and fs) and NODE_FUNCTION_ALLOW_EXTERNAL=moment,lodash for third‑party npm modules from the n8n/node_modules directory [9]. If using Task Runners, apply these environment variables to the Task Runner process instead of the main n8n instance. For more on secure self-hosting configuration, see the self‑hosting security guide.

When should you use the Code node over built‑in nodes or expressions?

Use the Code node when built‑in nodes don’t provide the specific data transformation, calculation, or logic needed—for example, restructuring deeply nested arrays, implementing custom aggregation algorithms, or applying business rules that span multiple items. For simple field mapping, prefer the Set node or expressions, which are faster and more maintainable. [4]

Python code in the Code node averages 25.5 ms per execution compared to 0.68 ms for JavaScript due to WebAssembly overhead. A single Code node with Python replaces approximately 15 built‑in nodes for complex logic, yet for lightweight transformations, built‑in nodes drastically reduce execution overhead and improve readability. [10] For a full reference of all built-in methods available in the Code node, consult the n8n documentation. For architecture-level scaling of Code node workloads, see the architecture & scaling guide.

References

This guide is for informational purposes only. For the most current and authoritative information, always refer to the official n8n website (n8n.io) and the n8n documentation. Product details and features may change over time.

Leave a Reply

Your email address will not be published. Required fields are marked *