D: n8n is a powerful workflow automation tool that lets you connect various apps and services without writing code. But when you need to implement complex logic, the Code Node becomes your secret weapon! π»β¨
In this guide, we’ll explore 10 real-world examples of how to use the Code Node in n8n to handle advanced data processing, custom transformations, and dynamic decision-making.
πΉ What is the Code Node?
The Code Node in n8n allows you to write JavaScript (Node.js) or Python code directly inside your workflow. This means you can:
β
Process & transform data dynamically
β
Implement custom calculations
β
Call external APIs with complex logic
β
Manipulate JSON, arrays, and objects
β
Add conditional branching beyond what regular nodes offer
π₯ 10 Powerful Code Node Examples
1οΈβ£ Format & Clean Raw Data
Need to standardize messy data? Use the Code Node to trim whitespace, convert cases, or remove duplicates.
// Clean & format names
const inputData = $input.all();
const output = inputData.map(item => ({
cleanName: item.json.name.trim().toUpperCase(),
email: item.json.email.toLowerCase()
}));
return output;
2οΈβ£ Merge Data from Multiple Sources
Combine data from different APIs or databases into a single output.
const dataA = $input.all()[0].json; // From HTTP Request Node
const dataB = $input.all()[1].json; // From Google Sheets
return [{ ...dataA, ...dataB }];
3οΈβ£ Dynamic IF-ELSE Conditions
Go beyond basic IF conditionsβimplement multi-layered logic.
const score = $input.first().json.score;
let grade;
if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else grade = "C";
return [{ grade }];
4οΈβ£ Generate Custom Reports in JSON/CSV
Process raw data into structured reports.
const salesData = $input.all();
const report = salesData.map(sale => ({
month: sale.json.month,
revenue: sale.json.amount * 0.9 // Apply 10% tax
}));
return report;
5οΈβ£ Call External APIs with Authentication
Handle OAuth, API keys, or custom headers.
const axios = require('axios');
const response = await axios.get('https://api.example.com/data', {
headers: { 'Authorization': 'Bearer YOUR_TOKEN' }
});
return response.data;
6οΈβ£ Date & Time Calculations
Calculate deadlines, time differences, or format dates.
const now = new Date();
const dueDate = new Date(now.setDate(now.getDate() + 7)); // +7 days
return [{ due: dueDate.toISOString().split('T')[0] }];
7οΈβ£ Validate & Filter Data
Remove invalid entries before further processing.
const users = $input.all();
const validUsers = users.filter(user =>
user.json.email.includes('@') && user.json.age > 18
);
return validUsers;
8οΈβ£ Generate Random Test Data
Create mock data for testing workflows.
const mockUsers = Array(5).fill().map((_, i) => ({
id: i + 1,
name: `User_${i}`,
value: Math.floor(Math.random() * 100)
}));
return mockUsers;
9οΈβ£ Advanced Error Handling
Catch and manage errors gracefully.
try {
const data = $input.first().json;
if (!data.email) throw new Error("Email missing!");
return [{ success: true }];
} catch (error) {
return [{ error: error.message }];
}
π Loop & Batch Processing
Process large datasets in chunks.
const bigData = $input.first().json.data;
const chunkSize = 50;
const batches = [];
for (let i = 0; i < bigData.length; i += chunkSize) {
batches.push(bigData.slice(i, i + chunkSize));
}
return batches;
π Pro Tips for Using Code Node
β Use $input
to access workflow data.
β return
must be an array of objects.
β Install npm packages via n8n's “External Libraries” feature.
β Debug with `console.log()βoutput appears in the “Execution” tab.
π― Conclusion
The Code Node unlocks endless possibilities in n8n workflows. Whether you're cleaning data, calling APIs, or implementing complex logic, itβs the ultimate tool for power users.
Try these examples and customize them for your needs! π Which one will you implement first? Let us know in the comments! π¬π
#n8n #Automation #Workflow #NoCode #LowCode #JavaScript #Python