Automation

Getting Started with n8n Code Node for JavaScript

Learn to use the n8n Code Node for advanced JavaScript workflows. Step-by-step guidance ensuring proper data structures and avoiding common mistakes.

4 min read

Learn to use the n8n Code Node effectively for writing custom JavaScript workflows. This guide walks you through its setup, key features, limitations, and common mistakes to avoid.

Understanding the n8n Code Node

The n8n Code Node enables users to write multi-line JavaScript or Python code within an n8n workflow. It is especially useful for complex data transformations, logical operations, or tasks that exceed the limitations of n8n's expressions. The Code Node executes as a single step in your workflow, either for all inputs at once or individually for each item, depending on its mode configuration.

Prerequisites for Using the Code Node

Before you start using the Code Node, ensure you meet the following requirements:

prerequisites

  • Access to an n8n instance (cloud or self-hosted).
  • Basic understanding of JavaScript and JSON structures.
  • A configured Google Sheets integration for demonstration purposes.

Steps to Create a Workflow with the Code Node

This section provides step-by-step instructions to integrate the Code Node into your workflow.

steps

  1. Create a New Workflow

    • Open your n8n workspace and start a new workflow.
    • Add a Manual Trigger node to kick off the workflow.
  2. Add the Code Node

    • Search for "Code" in the node library and drag it to the canvas.
    • Link it to the Manual Trigger.
  3. Configure the Code Node

    • Set the language to JavaScript.
    • Select the Mode:
      • Run Once for All Items: Processes data as a batch.
      • Run Once for Each Item: Processes one input at a time.
  4. Write JavaScript Code
    Insert your custom JavaScript code to manipulate, transform, or extract data.

  5. Return Properly Formatted Output
    Ensure your code outputs data in the expected array-based JSON structure.

  6. Test the Node

    • Click on Execute Node to test and verify your code's result.

Writing JavaScript in the Code Node

Below is a practical example of using the Code Node to calculate the total order values from sample order data retrieved from Google Sheets.

Code for Calculating Total Order Values

const inputData = $input.all();
let orderTotals = {};

// Parse input data to calculate totals
inputData.forEach(item => {
    // Access data fields using item.json
    const orderId = item.json.order_id;
    const price = parseFloat(item.json.total_price);

    if (!orderTotals[orderId]) {
        orderTotals[orderId] = 0;
    }
    orderTotals[orderId] += price;
});

// Format output into n8n-compatible JSON array structure
const outputData = Object.keys(orderTotals).map(orderId => ({
    json: {
        order_id: orderId,
        order_total: orderTotals[orderId].toFixed(2)
    }
}));

return outputData;
  • $input.all() retrieves all input items into a single array.
  • The orderTotals object is used to accumulate totals for each unique order.
  • The result is returned as a JSON array to meet n8n's expected output format.

Limits and Alternatives for Code Node Usage

When using the Code Node, there are some important limitations to consider:

Output Data Structure in n8n

The output of every node in n8n, including the Code Node, must be an array of JSON objects. This structure allows seamless processing between nodes. Here's an example of the expected structure:

before after

Before

Incorrect Output

json
{
    "order_id": "001",
    "order_total": 500
}
After

Correct Output

json
[
    {
        "json": {
            "order_id": "001",
            "order_total": 500
        }
    }
]

For binary data (e.g., files or images), you must include a binary field in addition to the json structure.

Takeaways

FAQ

Can I use npm packages in the n8n Code Node?

In cloud-hosted n8n instances, you cannot install external npm packages. For self-hosted n8n instances, some built-in packages are supported, but you may need to configure the environment to enable custom libraries.

What happens if the output JSON structure is incorrect?

If the output JSON structure doesn't follow n8n's requirements (a JSON array with key json), the workflow will fail, and an error will occur. Always ensure the output is properly formatted.

Can the Code Node make API calls?

No, the Code Node does not support direct API calls. Use the HTTP Request Node for this functionality.


Official reference: n8n documentation.