Hello! Welcome back.
In our last lesson, we saw how to summarize many data items into one, getting a brief taste of the Code node's power for aggregation. You learned to use $input.all() to process an entire dataset in one go, a pattern that likely felt familiar from your development background.
Today, we're doing a deep dive into that very tool. The learning outcome for this lesson is to use the Code node to write custom JavaScript for complex transformations. While n8n's strength is its visual, no-code interface, the Code node is the bridge to the world of programming you already know. It's the ultimate escape hatch, ensuring that no business logic is too complex and no data transformation is out of reach. We'll explore its core mechanics, when to use it, and just as importantly, when not to.
1. The Foundation: How n8n Structures Data
Before writing any custom code, we must be absolutely clear on the data structure we'll be manipulating. As we've seen, n8n passes data between nodes in a specific format. Misunderstanding this is the most common source of errors in the Code node.
Let's solidify this foundational concept by reviewing the official n8n documentation.
Understanding the data structure
The n8n documentation provides a clear, concise explanation of its core data structure. Understanding this is non-negotiable for using the Code node.
Please read the sections titled 'Data structure of n8n' and 'Creating data sets with the Code node'. Pay close attention to the concept of an 'array of objects' and how each object must be wrapped with a json key. This structure, [{ json: { ... } }, { json: { ... } }], is what you receive as input and what you must return as output.
The key takeaway is that you're almost always working with an array of items. Even if a node only outputs one item, it's still an array with a single element. Your code will need to process this array and return a new array in the same format.
2. Anatomy of the Code Node
Now that we have the data structure theory down, let's see it in practice. The Code node provides a rich environment with special variables and helpers to make your life easier.
The following video is an excellent and comprehensive guide to the Code node. We will watch it in a few parts.
build anything with the n8n code node, here’s how
Let's start with the fundamentals of how data flows in and out of the Code node and what built-in tools are available. This clip from David Ondrej's channel explains it well.
Watch from 01:53 to 06:21. The video will cover: Input Data: How to access incoming data using $input.all() for all items and $input.json for a single item. Output Data: The importance of the return statement and the structure of the data you send to the next node. Built-in Helpers: An overview of powerful utilities like this.helpers.httpRequest, accessing data from non-adjacent nodes ($node['Node Name'].json), and variables like $now and $env.
This clip reinforces what you read in the documentation and introduces the toolkit available within the node. Being aware of helpers like this.helpers.httpRequest and the ability to pull data from any previous node by name ($node['...']) are game-changers for building complex workflows.
3. When to Use the Code Node: Practical Scenarios
The most important question isn't how to use the Code node, but when. You should reach for it when the task is difficult, repetitive, or impossible with standard nodes.
This next segment of the video gives four perfect examples.
build anything with the n8n code node, here’s how
Let's continue with the same video to see concrete scenarios where the Code node is the best tool for the job.
Watch from 06:21 to 12:26. The presenter covers four key use cases: Complex Grouping/Aggregation: Performing calculations that go beyond what the Aggregate node can do. Extending Node Functionality: Adding a capability that a pre-built node is missing (e.g., media uploads for the WordPress node). Utilizing Full API Power: Making custom API calls when a pre-built node's filters are too simplistic. Extracting Nested Data: Navigating and parsing complex JSON structures that are cumbersome to handle otherwise.
These scenarios highlight a common theme: the Code node is for custom logic. As a developer, this is your domain. Consider this example, which translates a typical Node.js script into an n8n workflow.
The Node.js Way:
You might write a script to fetch data, convert names to uppercase, and add a timestamp.
// Node.js example
const response = await axios.get('https://api.example.com/data');
const processedData = response.data.map(item => ({
id: item.id,
name: item.name.toUpperCase(),
processed_at: new Date().toISOString()
}));
The n8n Code Node Way:
In n8n, you'd use an HTTP Request node to fetch the data, then a Code node to perform the transformation. The code inside would be remarkably similar.
// n8n Code Node example
// Assumes the node is set to "Run Once for Each Item"
const item = $input.item.json;
item.name = item.name.toUpperCase();
item.processed_at = new Date().toISOString();
return item;
(This is adapted from the "NodeJS to n8n" guide you can explore later). The logic is the same, but it's encapsulated within a single, reusable workflow step.
4. A Developer's Superpower: AI-Assisted Coding
You don't have to write every line of code from scratch. The Code node integrates an AI assistant, and you can leverage tools like ChatGPT to accelerate your work significantly. Given your background, you know how to describe logic; now you can have an AI translate that description into the required JavaScript.

Watch this final clip from the video to see this in action.
build anything with the n8n code node, here’s how
This clip demonstrates how to use ChatGPT to write the JavaScript for your Code node, even for a moderately complex task.
Watch from 12:26 to 15:30. Notice the prompt structure: the user describes the goal, provides the input data structure, and specifies the desired output. This is a highly effective workflow for leveraging AI.
Test your understanding!
You have a list of user items coming into your workflow. Each item has the structure { "name": "Jane Doe", "last_login": "2023-10-27T10:00:00.000Z" }.
Write the JavaScript for a Code node (running in the default "For Each Item" mode) that adds a new field called status.
- If
last_loginis within the last 30 days,statusshould be "active". - Otherwise,
statusshould be "inactive".
The node should return the modified item.
Show answer
Here is a solution. Note the use of new Date() to handle the date strings and perform the comparison.
// Get the current item's data
const item = $input.item.json;
// Calculate the date 30 days ago
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
// Parse the user's last login date
const lastLoginDate = new Date(item.last_login);
// Compare the dates and set the status
if (lastLoginDate > thirtyDaysAgo) {
item.status = 'active';
} else {
item.status = 'inactive';
}
// Return the entire modified item
return item;
This code would be placed in a Code node. It reads the incoming item, applies the business logic, modifies the object, and returns it for the next node in the workflow.
5. When NOT to Use the Code Node
Knowing when to use a powerful tool is only half the battle. Knowing when not to use it is just as important for building clean, maintainable workflows. Using the Code node for a simple task that a built-in node can handle is like using a sledgehammer to crack a nut—it works, but it's messy and inefficient.
Before you jump into the Code node, always ask: "Is there a standard node for this?"
The video you've been watching has an excellent summary of alternatives.
build anything with the n8n code node, here’s how
Finally, let's review which standard n8n nodes you should prefer for common tasks instead of writing custom code.
Watch from 17:33 to the end. The video lists several powerful nodes that you should master, including: If / Switch: For simple conditional logic. Edit Fields (Set): For renaming, adding, or removing fields. Filter: For selectively keeping or discarding items. HTTP Request: For making API calls without writing fetch/axios code. Date & Time: For date manipulations.
Conclusion
You've now taken a comprehensive look at the n8n Code node. It's the most powerful and flexible node in your toolkit, allowing you to leverage your existing JavaScript skills to solve any automation challenge.
Key Takeaways:
- The Code node is your escape hatch for complex logic that standard nodes can't handle.
- Master the data structure: Everything in n8n is an array of items, where your data lives in the
jsonproperty:[{ json: {...} }]. Your node must receive this and return this. - Leverage built-in helpers like
$node,$env, andthis.helpers.httpRequestto write more powerful and concise code. - Use AI as a co-pilot to generate boilerplate code, allowing you to focus on the logic.
- Know when to say no: Always prefer a dedicated, no-code node if it can do the job cleanly. This makes your workflows easier for others (and your future self) to understand.
In this lesson, we saw how the Code node can make custom HTTP requests. This often requires authentication. In our next lesson, we'll tackle that head-on by learning how to set up credentials securely for third-party services, a critical step for any real-world integration.