How to use Code Node in n8n - Data Structure & Limitations | Python in n8n

Learn how to use the n8n Code node to write custom JavaScript or Python code for data manipulation, including execution modes and data structure tips.

Table of Contents

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 Code node.
  • 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:

  1. 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.
  2. 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.

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

  1. Add two Google Sheets nodes 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).
  2. Execute each node to confirm data retrieval.

Step 2: Merge the Data

  1. Add a Merge node.
  2. Connect both Google Sheets nodes as inputs.
  3. Set the Merge mode to Combine.
  4. Select the field to merge on, e.g., order ID.
  5. 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

  1. Add a Code node connected to the Merge node.
  2. Set Mode to Run once for all items.
  3. 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 orderId and orderTotal.

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 orderId and its summed orderTotal.
  • The total is rounded to two decimal places using .toFixed(2).

Step 4: Execute and Verify Output

  • Execute the Code node.
  • 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 json key holding the actual data.
  • Example of a single item:
[
  {
    "json": {
      "orderId": "001",
      "orderTotal": 1250.50
    }
  }
]
  • When working with files or binary data, use the binary key inside each item:
{
  "binary": {
    "data": {
      "data": "<base64-encoded content>",
      "mimeType": "application/pdf",
      "fileName": "document.pdf",
      "fileExtension": "pdf"
    }
  }
}
  • The Code node 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:
    The Code node cannot read/write files or make HTTP requests. Use dedicated nodes for these tasks:

  • 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 json key.
  • 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


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.

Frequently Asked Questions

The Code node can run once for all input items together or run once per input item, allowing flexible data processing strategies.

In JavaScript, use $input.all() to access all items as an array; in Python (beta), use _input.all() for the same purpose.

Python support is currently in beta, so some features and integrations may be limited or behave differently compared to JavaScript.

Set the Code node to 'run once for all items' mode and use $input.all() or _input.all() to process the entire dataset at once.

Yes, unlike expressions, the Code node supports multi-line JavaScript or Python scripts for advanced data manipulation within workflows.

Dheeraj Sharma

Dheeraj Sharma

AI Systems Builder
Creator of the n8n Zero to Hero course (42 lessons, 31+ hours). I help solopreneurs build AI systems that grow revenue without growing workload.

Get the n8n Mastery Bundle

All workflows, cheat sheets, and premium resources from the entire course in one package.

Get Premium Resources