Based on a tutorial by n8n
Are you hitting roadblocks with your n8n workflows? Finding yourself limited by the basic nodes and looking to take your automation skills to the next level?
I've summarized the second video of n8n's advanced course to help you quickly master some of the most powerful features: expressions, the code node, and the HTTP node. These three elements are what separate beginners from power users in the n8n ecosystem.
Quick Navigation
Mastering n8n Expressions
Building on the beginner course, this advanced video dives deeper into expressions - the heart of data manipulation in n8n. Expressions are small JavaScript snippets enclosed in curly brackets that let you access and transform data.
Key Points:
- Expressions are JavaScript snippets written between curly brackets {{ }}
- You can drag and drop items to automatically create expressions
- Beyond basic data access, expressions support arithmetic operations and complex transformations
- n8n provides built-in data transformation functions for common tasks
Useful Built-in Functions:
// Check if an object has key-value pairs
{{ $isEmpty(item) }}
// Check if object has a specific field
{{ $hasField(item, 'fieldName') }}
// Remove duplicates from array
{{ $removeDuplicates(myArray) }}
// Find difference between arrays
{{ $arrayDifference(array1, array2) }}
// Extract domain from email
{{ $extractDomain('maxim@acme.com') }} // Returns 'acme.com'
My Take:
While the drag-and-drop feature is convenient for beginners, I recommend practicing writing expressions manually. This builds muscle memory and gives you a deeper understanding of how data flows through your workflows. The documentation link mentioned in the video is essential reading - bookmark it for reference!
Working with Dates Using Luxon
Date manipulation is often challenging in programming, but n8n integrates the Luxon library to make working with dates and times much easier in your workflows.
Key Points:
- Access current date/time with {{ $now }}
- Convert between date objects and strings with .toString() and .fromFormat()
- n8n passes dates as strings between nodes, requiring conversion back to date objects for manipulation
- Luxon makes common date operations straightforward
Date Manipulation Examples:
// Get current date and time as object
{{ $now }}
// Convert to readable string
{{ $now.toString() }}
// Get today's date with midnight timestamp
{{ $today }}
// Format date with specific pattern
{{ $now.toFormat('yyyy-MM-dd') }}
My Take:
The most common mistake I see with date handling in n8n is forgetting that dates are passed as strings between nodes. Always convert back to a date object with Luxon before performing operations - this simple step will save you hours of debugging!
The Code Node: Extending n8n's Flexibility
The code node is where n8n truly shines, allowing you to extend functionality beyond what's available in native nodes by executing custom JavaScript or Python code on your workflow data.
Key Points:
- Choose between JavaScript or Python for your code
- Two operation modes: "Run once for all items" or "Run once for each item"
- Must return a list/array of JSON objects (or a single object in "each item" mode)
- Access input items with built-in variables like $input.all and $json
- Great for calculations across items (sums, averages, distributions)
Code Node Basics:
// Run once for all items mode
// Must return an array of objects
const newItems = [];
for (const item of $input.all) {
// Process each item
newItems.push({
// Create new object with transformed data
myNewField: item.json.someValue * 2
});
}
return newItems;
// Return empty result (still valid)
return [{}];
// Run once for each item mode
// Must return a single object
$input.item.json.myNewField = $input.item.json.someValue * 2;
return $input.item;
My Take:
The code node is extremely powerful but use it judiciously. I find it's best to first check if your goal can be accomplished with native nodes before resorting to custom code. This keeps workflows more maintainable. When you do need code, the "Run once for all items" mode is excellent for aggregate operations, while "Run once for each item" is cleaner for individual transformations.
The HTTP Node: Working with APIs
Think of the HTTP node as "Postman in a node" - it's your gateway to connecting with external services through their APIs when a native integration isn't available.
Key Points:
- Configure all parts of HTTP requests: headers, body, query parameters, URL, etc.
- Advanced settings handle pagination, timeouts, and error handling
- Can use credentials from other nodes (saving authentication headaches)
- Import curl commands to instantly configure the node
- Extends access to services without native nodes
My Take:
The curl import feature is a massive time-saver that wasn't immediately obvious to me when I started with n8n. When working with a new API, I often ask ChatGPT to generate the curl command for me based on the API documentation, then paste it directly into the HTTP node. This approach skips the tedious process of configuring headers, authentication, and request bodies manually.
Practical Code Node Examples
The video demonstrates practical applications of the code node through two examples: calculating a sum total across all items and computing average values for each item.
Example 1: Calculate Total Sum (Run once for all items)
- Creates a variable to hold the running total
- Loops through all items, adding their values to the total
- Returns a single object containing the sum
- Uses console.log for debugging during development
// Calculate total sum across all items
let total = 0;
for (const item of $input.all) {
total += item.json.totalOrderValue;
// Debug with console.log to trace values
console.log(total);
}
// Return single item with total
return [{ total }];
Example 2: Calculate Average for Each Item (Run once for each item)
- Works on each item individually
- Calculates average by dividing total order value by order count
- Adds new field to the existing item
- Returns the augmented item
// Calculate average order value for current item
const averageValue = $input.item.json.totalOrderValue / $input.item.json.orderCount;
// Add new field to current item
$input.item.json.averageValue = averageValue;
// Return modified item
return $input.item;
My Take:
The debugging approach shown in the video is invaluable. When your workflow isn't behaving as expected, liberal use of console.log() statements can quickly pinpoint issues. Remember that n8n's execution panel shows these logs - it's a built-in debugging environment that many users overlook!
HTTP Node in Action: Using Curl Import
The video concludes with a practical demonstration of the HTTP node's curl import feature to quickly set up an API request to People Data Labs.
Key Points:
- Copied a curl command from API documentation
- Used the "Import Curl" feature to automatically configure the HTTP node
- Adjusted the request parameters (setting size to 1)
- Successfully executed the request and received person data
- Used predefined credentials instead of hardcoded API key
My Take:
While the curl import feature is powerful, always review the imported settings before execution. Pay special attention to authentication details - you'll typically want to replace hardcoded API keys with n8n credentials for better security. Also, remove any test parameters that might consume API quotas unnecessarily when testing your workflow.
Comments
Post a Comment