• AI Fire
  • Posts
  • ⚡ Supercharge Your N8N Workflows The Complete Code Node Guide

⚡ Supercharge Your N8N Workflows The Complete Code Node Guide

Go past n8n's limits. Our guide covers the Code Node with JS for API calls, batch jobs, and dynamic file creation. Includes real, copy-paste examples.

📊 How comfortable are you with the n8n Code Node right now?

Login or Subscribe to participate in polls.

Table of Contents

Why The Code Node Is A Game-Changer for Automation

Have you ever felt limited by the built-in nodes in your n8n workflows? Many users avoid the Code Node, assuming it's too complex and requires advanced programming skills. But here's the truth: you can master it in just one afternoon. Once you do, it will unlock a new horizon of automation possibilities that platforms like Make or Zapier can hardly match.

zapier

The Code Node isn't just an auxiliary feature; it's the gateway to extending n8n's power beyond its usual limits. Equipped with built-in helpers and shortcuts, you can handle complex data manipulation, make external API calls, process information in batches, and even create files directly within your workflows.

In this comprehensive guide, we will dive deep into every aspect of the Code Node, from fundamental concepts to advanced techniques, using practical examples you can copy and paste directly into your workflows. By the end of this article, you will understand why the Code Node is the secret weapon that makes n8n incredibly powerful for advanced automation tasks.

Preparing Your Practice Environment

Before we get into the technical details, let's set up a practice environment. The best way to learn is by doing. You can start with a blank workflow and build the examples below, or use a pre-built template for reference.

To get started, create a new workflow in your n8n instance. We'll begin with a Start node and build out our Code Node scenarios from there.

start

Sample Data Structure

To make things easy to follow, we'll work with a sample dataset of order items. Imagine your input data is a JavaScript array of objects, where each object represents a product in an order:

sample-data

JavaScript

[
  {
    "productID": "SKU-001",
    "productName": "Laptop Pro 15 inch",
    "category": "Electronics",
    "price": 1200.00,
    "quantity": 1,
    "customerEmail": "[email protected]"
  },
  {
    "productID": "SKU-002",
    "productName": "Wireless Mouse",
    "category": "Accessories",
    "price": 25.50,
    "quantity": 2,
    "customerEmail": "[email protected]"
  },
  {
    "productID": "SKU-003",
    "productName": "USB-C Hub",
    "category": "Accessories",
    "price": 45.00,
    "quantity": 1,
    "customerEmail": "[email protected]"
  }
]

A key initial concept is using the Split Out node (or handling it directly in the Code Node) to convert this large data array into individual items. This transforms a single input containing all orders into multiple items, with each item holding one product's information. This allows us to process each product independently in subsequent nodes.

split-out
result

Learn How to Make AI Work For You!

Transform your AI skills with the AI Fire Academy Premium Plan - FREE for 14 days! Gain instant access to 500+ AI workflows, advanced tutorials, exclusive case studies and unbeatable discounts. No risks, cancel anytime.

Start Your Free Trial Today >>

Part 1: Basic Data Manipulation With The Code Node

The Two Processing Modes Of The Code Node

The Code Node offers two core operating modes that determine how it interacts with input data:

  1. Run Once for Each Item: Processes each item independently. This is the default and most common mode.

  2. Run Once for All Items: Processes the entire input data (an array of items) as a single unit.

We'll start with the individual item processing mode.

Building Your First Code Node

When you create a new Code Node, n8n provides a default code snippet:

JavaScript

for (const item of $input.all()) {
  item.json.myNewField = 1;
}
return $input.all();

This code loops through each input item and adds a new field named myNewField with a value of 1.

Practical Example: Standardizing Data And Creating New Fields

Let's look at a more practical example: from our order data, we'll calculate the total value for each product (price x quantity) and extract the domain name from the customer's email.

JavaScript

prompt
// Get the JSON data from the current item
const orderItem = $input.item.json;

// 1. Calculate the total value for each product line
const lineTotal = orderItem.price * orderItem.quantity;

// 2. Extract the domain from the customer's email using string manipulation
const email = orderItem.customerEmail;
const domain = email.substring(email.indexOf('@') + 1);

// 3. Return the original data along with the new fields
return {
  ...orderItem,         // Keep all original data
  lineTotal: lineTotal,
  customerDomain: domain
};
result

Detailed Code Breakdown

  • Variable Declaration and Data Access: We create a variable orderItem to hold all the data from the current item using $input.item.json. This is the core data access structure when working with individual items.

  • Simple Calculation: lineTotal is calculated using basic arithmetic multiplication.

  • String Manipulation: We used the substring and indexOf methods to extract the domain part from the email string. This is a typical example of data cleaning and standardization.

  • The Spread Operator (...): The ...orderItem syntax is an incredibly useful tool in modern JavaScript. It "spreads" all the properties of the original orderItem object into the returned object. Without it, the output would only contain the two new fields, lineTotal and customerDomain, losing all the original data.

Part 2: Calling External APIs To Enrich Data

One of the most powerful features of the Code Node is its ability to call external APIs to fetch additional information during workflow execution. This capability turns n8n into a flexible data orchestration hub, setting it apart from many other platforms.

Setting Up An API Call

Let's see how we can enrich our product data by using a free API to get barcode information. Assume we want to get more details about a product based on its productID (treating it as an EAN code).

JavaScript

prompt
const item = $input.item.json;
const url = `https://world.openfoodfacts.org/api/v0/product/${item.productID}.json`;

// Use the helper function to make an HTTP request
const response = await this.helpers.httpRequest({
  method: 'GET',
  url: url,
  json: true // Automatically parse the response as JSON
});

// Check if the product exists in the API
if (response.status === 0) {
  return {
    ...item,
    apiError: response.status_verbose
  };
}

// Extract the necessary information from the API response
return {
  ...item,
  productBrand: response.product.brands,
  imageUrl: response.product.image_url
};
result

Decoding Key Concepts

decoding-key-concepts
  • async and await Keywords: An API call is an asynchronous action. The await keyword tells the Code Node to "wait" until the API returns a result before executing the next lines of code. Without await, the code would continue running and try to access response before it exists, causing an error. While await requires an async function, the Code Node environment handles this implicitly for you.

  • Built-in Helper this.helpers.httpRequest: This is a special function provided by n8n to simplify making HTTP requests. You don't need to import complex libraries like axios or node-fetch. It handles much of the boilerplate, keeping your code clean.

prompt
  • Response Handling: Every API has its own response structure. Here, we check response.status to see if the call was successful, then extract fields like brands and image_url from the product object in the returned JSON.

prompt
  • Securely Storing API Keys: This example uses a public API. However, for APIs that require authentication, never hardcode your API key in the code. Instead, use n8n's Credentials feature to store keys securely and reference them in your node.

prompt

Part 3: Batch Processing - Interacting With All Data At Once

Sometimes, you need to analyze or process your entire dataset as a group rather than one item at a time. This is where "Run once for all items" mode becomes essential.

Switching To Batch Mode

In the Code Node's settings, change the "Execute Once" option from false (default) to true, or in newer versions, switch from "Run Once for Each Item" to "Run Once for All Items". Now, instead of $input.item, you'll work with the $items variable, which is an array containing all input items.

Example: Calculating Aggregate Statistics

Here's an example that calculates statistics across our entire product list: total revenue, number of unique products, and a category-based report.

JavaScript

prompt
// 1. Get all items by CALLING THE $items() FUNCTION
const allItems = $items();

// Now that we have a standard array, we can extract the JSON data from each item.
const allOrders = allItems.map(item => item.json);
const totalItems = allOrders.length;

// 2. Calculate the total revenue
const totalRevenue = allOrders.reduce((sum, order) => sum + order.price * order.quantity, 0);

// 3. Generate statistics by category
const categoryReport = allOrders.reduce((report, order) => {
  const category = order.category;
  const itemTotal = order.price * order.quantity;

  if (!report[category]) {
    report[category] = {
      totalSales: 0,
      itemCount: 0
    };
  }
  
  report[category].totalSales += itemTotal;
  report[category].itemCount += order.quantity;
  
  return report;
}, {});


// 4. Format the return object
return [{
  json: {
    totalRevenue: parseFloat(totalRevenue.toFixed(2)),
    totalItemsSold: totalItems,
    categoryReport: categoryReport,
    reportGeneratedAt: new Date().toISOString()
  }
}];
result

Analyzing The Batch Processing Code

batch-processing
  • Data Extraction: $items.map(item => item.json) is a crucial step to convert n8n's complex object array (containing json and binary properties) into a simple array of pure JSON data, which is easier to process.

  • The Power of reduce(): JavaScript's reduce() method is the perfect tool for accumulating a value from an array. We used it to calculate the total revenue and to create a more complex report object by grouping products by category.

  • Return Format: When processing all items at once, you must return an array of objects, even if there's only one result. This is why the result is wrapped in [{ json: {...} }].

Part 4: Creating Binary Files From Data

The ability to generate files directly from a workflow is one of the Code Node's most impressive features. You can convert your processed data into downloadable files like CSV, JSON, or even a beautiful HTML report.

Setting Up The File Creation Process

Here's how to create an HTML report file from the statistical data we calculated in the batch processing step.

JavaScript

prompt
// Assume this node receives data from the previous batch processing node
const reportData = $('5. Calculate Average Age').item.json;

// Start building the HTML string
let htmlContent = `
<html>
  <head>
    <title>Sales Report</title>
    <style>
      body { font-family: sans-serif; }
      table { border-collapse: collapse; width: 100%; }
      th, td { border: 1px solid #dddddd; text-align: left; padding: 8px; }
      th { background-color: #f2f2f2; }
    </style>
  </head>
  <body>
    <h1>Sales Report - ${new Date(reportData.reportGeneratedAt).toLocaleString('en-US')}</h1>
    <p><strong>Total Revenue:</strong> $${reportData.totalRevenue.toLocaleString('en-US')}</p>
    <p><strong>Total Items Sold:</strong> ${reportData.totalItemsSold}</p>
    <h2>Details by Category</h2>
    <table>
      <tr>
        <th>Category</th>
        <th>Total Sales</th>
        <th>Quantity Sold</th>
      </tr>
`;

// Add rows for each category
for (const category in reportData.categoryReport) {
  const data = reportData.categoryReport[category];
  htmlContent += `
    <tr>
      <td>${category}</td>
      <td>$${data.totalSales.toLocaleString('en-US')}</td>
      <td>${data.itemCount}</td>
    </tr>
  `;
}

// Close the table and HTML document
htmlContent += `
    </table>
  </body>
</html>
`;

// Prepare the binary data for n8n to understand
const binaryData = await this.helpers.prepareBinaryData(
  Buffer.from(htmlContent, 'utf8'),
  'report.html', // File name
  'text/html'    // MIME type
);

// Return the result with the binary property
return [{
  json: {
    reportGenerated: true,
    fileType: 'HTML'
  },
  binary: {
    data: binaryData
  }
}];
result

Breaking Down The File Creation Process

result
  • Referencing a Previous Node: $('Batch_Processing_Node_Name').item.json allows you to get data from a specific, previously executed node by using its name. This is crucial in complex workflows.

  • Building File Content: We create an HTML string using template literals (backticks `). This lets us embed dynamic data (like reportData.totalRevenue) directly into the string.

  • Buffer and Binary Data: Buffer.from(htmlContent, 'utf8') converts our text string into a binary format that computers can understand. Then, this.helpers.prepareBinaryData() packages this binary data along with a file name and a MIME type (a string identifier for the file type) so that n8n can handle it correctly.

  • Special Return Structure: To create a file, the returned item must have a specific structure containing both a json property (for metadata) and a binary property (containing the file itself).

Advanced Techniques And Best Practices

Error Handling

error

In a production environment, API calls don't always succeed. The network can fail, or the API might be down. Always wrap API calls in a try...catch block to handle these situations gracefully.

JavaScript

try {
  const response = await this.helpers.httpRequest({...});
  // Handle success
  return { ...item, data: response.someData };
} catch (error) {
  // Log the error and return a controlled error state
  // instead of crashing the entire workflow.
  console.error("API call failed for item:", item.json.productID, error.message);
  return { ...item, error: true, errorMessage: error.message };
}

Performance Optimization

performance-optimization

For large datasets, performance is a key concern:

  • Prefer Batch Processing: When possible, process data in batches instead of looping through thousands of items, as this minimizes code execution counts.

  • Add Delays: When calling APIs in a loop, add a small delay between calls to respect the API's rate limits and avoid being blocked.

  • Split Complex Nodes: Instead of writing a single 200-line Code Node, break down the logic into smaller, more focused Code Nodes. This makes debugging and maintenance much easier.

Debugging In The Code Node

debug

One of the most critical skills is debugging. The Code Node provides a simple yet effective debugging tool: console.log().

You can place console.log(variable_to_inspect) anywhere in your code. When the workflow runs, the output will be printed:

  • For n8n desktop: In the Developer Tools Console window.

  • For n8n server: In the n8n process's log file.

This is the best way to check the value of variables, inspect the structure of API responses, or see if your code is reaching a certain point.

Getting Help From AI

You don't need to be a JavaScript expert to write complex code. Generative AI tools like ChatGPT, Claude, or Perplexity can be powerful programming assistants.

Example of an effective prompt:

prompt
"I'm writing code in an n8n Code Node. Here is my current code:

const allOrders = $items.map(item => item.json);
// ... (paste your code here)

The input $items is an array of orders, where each order has customerEmail and lineTotal properties.

I need you to modify this code to group the orders by customerEmail and then calculate the sum of lineTotal for each customer. The final result should be an array of objects, where each object contains the email and totalSpent. Please write the code for me."

By providing clear context, your current code, and a specific request, you can get a near-perfect code snippet to paste into your workflow.

Conclusion: Your Next Steps On The n8n Journey

Mastering the Code Node transforms n8n from a simple automation tool into a powerful data processing and workflow orchestration platform. With these four core concepts - individual item processing, API integration, batch operations, and file creation - you are now equipped to tackle almost any complex automation challenge.

The key to success is to start simple and gradually increase complexity. Begin with basic data manipulation, then add external API calls, experiment with batch processing, and finally, explore file creation. Each technique builds on the last, forming a comprehensive toolkit.

Remember, you don't need to memorize every syntax detail. Focus on understanding the concepts and patterns, then leverage n8n's documentation and AI tools to help with specific code implementation.

Start practicing today. Open n8n, experiment with your own data, and you will soon discover automation possibilities you never thought possible. The Code Node isn't just a feature - it's your gateway to unlimited workflow potential. The only limit is your imagination.

If you are interested in other topics and how AI is transforming different aspects of our lives or even in making money using AI with more detailed, step-by-step guidance, you can find our other articles here:

How would you rate the quality of this AI Workflows article? 📝

Login or Subscribe to participate in polls.

Reply

or to participate.