Overview
In this tutorial, you will learn how to effectively use the Code node in n8n to write custom JavaScript or Python code for data transformation and manipulation. You will explore how to handle multiple input items, understand the required data structure for outputs, and learn about the limitations of the Code node. This guide also includes a practical example of merging and processing data from Google Sheets and writing custom logic to calculate total order amounts.
What is the Code Node in n8n?
The Code node in n8n allows you to run custom scripts written in JavaScript or Python (currently in beta). Unlike expressions, which are limited to single-line code snippets, the Code node supports multi-line code and runs as an independent step within your workflow.
Key Features:
- Write multi-line JavaScript or Python code.
- Manipulate, filter, or generate new data objects.
- Choose between two execution modes to control how the code runs against input items.
For a deeper understanding of how data flows through n8n, consider reviewing Understanding Data in n8n, which explains item-level processing and data structures.
Setting Up the Code Node
Step 1: Add a Trigger
Start by adding a trigger node to your workflow. For testing, the Manual Trigger node works best.
Step 2: Add the Code Node
- Click the
+button to add a new node. - Search for "Code" and select the
Codenode. - The node will appear with default multi-line code stub.
Step 3: Select Language
- In the Code node settings, choose the language you want to work with:
- JavaScript (default and fully supported)
- Python (beta, with some limitations)
Understanding Code Node Parameters
Mode: How Your Code Executes
The Code node has two execution modes:
Run once for all items
The code runs once, processing all input items together as an array.- Use
$input.all()in JavaScript or_input.all()in Python to access all items.
- Use
Run once for each item
The code runs once per input item.- Use
$input.item(JavaScript) or_input.item(Python) to access the current item.
- Use
Default behavior in the Code node is typically "Run once for all items", enabling you to manipulate the entire dataset at once.
Choosing the correct mode is important, especially when combining loops with conditions. For more on this, see Master Conditional Logic in n8n.
Accessing Data Inside the Code Node
JavaScript
- Use the
$prefix to access input data and other workflow context objects. - Example:
$input.all()returns an array of all input items. - Other useful objects include
$execution,$binary, and$node.
Python
- Use the
_prefix instead of$to access similar objects. - Example:
_input.all()returns all input items.
Note: Python support is currently in beta, so some features or integrations may be limited.
Example: Calculating Total Order Amounts from Google Sheets Data
Let's walk through a practical example where you fetch order data from two Google Sheets, merge them, and then calculate the total order amount per unique order using the Code node.
Step 1: Fetch Data from Google Sheets
Add two
Google Sheetsnodes with the Get Rows operation:- First node: Get order headers (e.g., Order ID, Customer Info).
- Second node: Get order details (e.g., Product ID, Unit Price, Total Price).
Execute each node to confirm data retrieval.
Step 2: Merge the Data
- Add a
Mergenode. - Connect both Google Sheets nodes as inputs.
- Set the Merge mode to Combine.
- Select the field to merge on, e.g.,
order ID. - Execute the Merge node to combine the datasets.
For more details on the merge process, refer to the n8n Merge node documentation{:target="_blank"}.
Step 3: Add and Configure the Code Node
- Add a
Codenode connected to theMergenode. - Set Mode to Run once for all items.
- Write JavaScript code to:
- Loop through all merged items.
- Sum the total price for each unique order ID.
- Return a new array of objects with
orderIdandorderTotal.
Sample JavaScript Code
// Initialize an object to store totals per order
const orderTotals = {};
// Loop through all input items
for (const item of $input.all()) {
const orderId = item.json.orderId;
const price = Number(item.json.totalPrice);
// Initialize order total if not present
if (!orderTotals[orderId]) {
orderTotals[orderId] = 0;
}
// Add the current item's price to the total
orderTotals[orderId] += price;
}
// Prepare the output array
const results = [];
for (const id of Object.keys(orderTotals)) {
results.push({
json: {
orderId: id,
orderTotal: Number(orderTotals[id].toFixed(2)), // rounded to 2 decimals
},
});
}
// Return the results in the required format
return results;
Explanation
$input.all()provides all 291 merged records.- The code accumulates the total price per unique
orderId. - The output is an array of JSON objects, each with
orderIdand its summedorderTotal. - The total is rounded to two decimal places using
.toFixed(2).
Step 4: Execute and Verify Output
- Execute the
Codenode. - The output will show unique order IDs with their corresponding total amounts.
- The number of output items will be fewer than input items because duplicates are combined.
After this, you might want to summarize or further aggregate your results. The Aggregate Node in n8n is a great tool to use after loops or code processing for such purposes.
Understanding n8n Data Structure in Code Node
In n8n, data passed between nodes must follow a specific structure:
- Data is always an array of items (even if there is one item).
- Each item is an object with a
jsonkey holding the actual data. - Example of a single item:
[
{
"json": {
"orderId": "001",
"orderTotal": 1250.50
}
}
]
- When working with files or binary data, use the
binarykey inside each item:
{
"binary": {
"data": {
"data": "<base64-encoded content>",
"mimeType": "application/pdf",
"fileName": "document.pdf",
"fileExtension": "pdf"
}
}
}
- The
Codenode output must follow this structure; otherwise, n8n will throw an error.
For more on working with data formats and structures, see Understanding Data in n8n.
Limitations of the Code Node
When using the Code node, be aware of these limitations:
No external libraries in n8n Cloud:
You cannot import npm packages or external Python libraries in the cloud-hosted version.No file system or HTTP access:
TheCodenode cannot read/write files or make HTTP requests. Use dedicated nodes for these tasks:HTTP Requestnode{:target="_blank"}Read Binary Filenode{:target="_blank"}
Python support is beta:
Some features or integrations may not work perfectly.
If you need to process large datasets in batches, consider using the SplitInBatches node{:target="_blank"} to manage data flow efficiently.
Common Mistakes and Troubleshooting
1. Not Returning the Correct Data Structure
- Always return an array of objects, each with a
jsonkey. - Returning raw arrays or objects without wrapping will cause errors.
2. Misusing Execution Modes
- Using Run once for each item when you want to process all data at once can cause performance issues or incorrect logic.
- Choose the mode based on whether your logic depends on individual items or the entire dataset.
3. Incorrect Data Access Syntax
- For JavaScript, use
$input.all()or$input.item. - For Python, use
_input.all()or_input.item. - Using the wrong prefix or method will result in undefined variables.
4. Trying to Use Unsupported Features
- Avoid importing external packages in the cloud version.
- Do not attempt to access the file system or make HTTP calls inside the Code node.
Quick Reference Cheat Sheet
| Concept | JavaScript Syntax | Python Syntax (Beta) |
|---|---|---|
| Access all input items | $input.all() |
_input.all() |
| Access current input item | $input.item |
_input.item |
| Return data | return [{ json: {...} }]; |
return [{ "json": {...} }] |
| Run mode (all items) | Select Run once for all items | Same |
| Run mode (each item) | Select Run once for each item | Same |
| Add new field to item | item.json.newField = value |
item['json']['newField'] = value |
Additional Resources
- n8n Code Node Documentation{:target="_blank"}
- Working with Data in n8n{:target="_blank"}
By mastering the Code node, you unlock the power to write advanced data transformations and custom logic within your n8n workflows. This lesson prepares you to handle complex scenarios where built-in nodes or expressions fall short, enabling you to build robust, flexible automations.