D: Are you looking to supercharge your n8n workflows with custom JavaScript/Python snippets? The Code Node is your ultimate weapon! π»β¨ Whether you’re transforming messy API responses, implementing advanced calculations, or integrating unique business logic, this guide will walk you through real-world use cases with clear examples.
π What is the n8n Code Node?
The Code Node lets you inject custom JavaScript/Python code into your workflows. Unlike pre-built nodes, it offers unlimited flexibility to:
- Manipulate data (e.g., filtering, sorting, or reformatting JSON).
- Add conditional logic (e.g., “Send an alert if stock prices drop by 10%”).
- Call external APIs dynamically.
- Debug workflows by logging intermediate data.
π Example: Convert a raw API date ("2023-10-05T14:30:00Z"
) into a user-friendly format ("Oct 5, 2023"
).
// JavaScript Code Node
const rawDate = $input.all()[0].json.date;
const formattedDate = new Date(rawDate).toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric'
});
return { formattedDate }; // Outputs: { "formattedDate": "Oct 5, 2023" }
π Top 5 Practical Use Cases
1οΈβ£ Data Transformation
Scenario: An e-commerce API returns product data in a nested structure, but you need a flattened CSV for reporting.
const products = $input.all()[0].json.products;
const simplified = products.map(product => ({
name: product.title,
price: product.variants[0].price,
stock: product.variants[0].inventory_quantity
}));
return simplified; // Output: [{ name: "T-Shirt", price: "19.99", stock: 42 }, ...]
2οΈβ£ Conditional Workflow Branching
Scenario: Only notify Slack if a new leadβs “priority” field is “high”.
const lead = $input.all()[0].json;
if (lead.priority === "high") {
return [ { shouldNotify: true, lead } ]; // Triggers Slack node
} else {
return [ { shouldNotify: false } ]; // Skips notification
}
3οΈβ£ Custom API Requests
Scenario: Fetch weather data from OpenWeatherMap, but only return midday forecasts.
const axios = require('axios');
const response = await axios.get('https://api.openweathermap.org/data/2.5/forecast?q=Berlin&appid=YOUR_API_KEY');
const middayForecasts = response.data.list.filter(item =>
item.dt_txt.includes("12:00:00")
);
return middayForecasts;
4οΈβ£ Error Handling & Logging
Scenario: Log errors to a Google Sheet before retrying failed steps.
try {
const result = someUnstableOperation();
return result;
} catch (error) {
console.error("Error details:", error); // View logs in n8n's "Execution" tab
throw error; // Triggers n8n's error workflow
}
5οΈβ£ Merging Data from Multiple Nodes
Scenario: Combine CRM contacts (Node 1) with support tickets (Node 2) into a unified dataset.
const contacts = $input.all()[0].json;
const tickets = $input.all()[1].json;
const merged = contacts.map(contact => ({
...contact,
tickets: tickets.filter(ticket => ticket.email === contact.email)
}));
return merged;
π‘ Pro Tips for the Code Node
- Accessing Input Data: Use
$input.all()
(all items) or$input.first()
(first item). - Libraries: Import npm packages like
axios
orlodash
directly. - Debugging:
console.log()
outputs appear in the “Execution” tab. - Python? Enable it in n8n settings (
EXECUTION_TIMEOUT=100
for long scripts).
π Final Thoughts
The Code Node turns n8n into a no-code/low-code hybrid tool. Start small (e.g., formatting dates), then gradually tackle complex logic like AI integrations or multi-step data pipelines.
Challenge: Try building a workflow that fetches GitHub issues, filters by label, and posts summaries to Discordβall with a Code Node! π
π More resources:
Whatβs your favorite Code Node hack? Share in the comments! π