| name | n8n-code-javascript |
| description | Write JavaScript code in n8n Code nodes. Use when writing custom JavaScript, accessing data in Code nodes, transforming data programmatically, handling multiple items, or debugging Code node errors. Use when this capability is needed. |
| metadata | {"author":"fazer-ai"} |
n8n Code JavaScript
Expert guidance for writing JavaScript in n8n Code nodes.
Based on n8n-skills by Romuald Członkowski
Code Node Modes
Run Once for All Items
Process all items together. Most common mode.
const items = $input.all();
return items.map(item => ({
json: {
...item.json,
processed: true
}
}));
Run Once for Each Item
Process each item separately.
const data = $input.item.json;
return {
json: {
...data,
processed: true
}
};
Accessing Data
Current Node Input
const items = $input.all();
const first = $input.first();
const current = $input.item;
const data = $input.first().json;
Previous Nodes
const nodeData = $node["Node Name"].all();
const firstItem = $node["HTTP Request"].first().json;
const inputItems = $input.all();
Execution Context
const workflowId = $workflow.id;
const workflowName = $workflow.name;
const executionId = $execution.id;
const apiKey = $env.API_KEY;
const myVar = $vars.myVariable;
Common Patterns
Transform All Items
const items = $input.all();
return items.map(item => ({
json: {
id: item.json.id,
name: item.json.name.toUpperCase(),
createdAt: new Date().toISOString()
}
}));
Filter Items
const items = $input.all();
return items.filter(item => item.json.status === 'active');
Aggregate Data
const items = $input.all();
const total = items.reduce((sum, item) => sum + item.json.amount, 0);
const count = items.length;
return [{
json: {
total,
count,
average: total / count
}
}];
Group By
const items = $input.all();
const grouped = {};
for (const item of items) {
const key = item.json.category;
if (!grouped[key]) grouped[key] = [];
grouped[key].push(item.json);
}
return Object.entries(grouped).map(([category, items]) => ({
json: { category, items, count: items.length }
}));
Fetch External Data
const response = await fetch('https://api.example.com/data', {
headers: { 'Authorization': `Bearer ${$env.API_TOKEN}` }
});
const data = await response.json();
return [{ json: data }];
Error Handling
const items = $input.all();
return items.map(item => {
try {
const parsed = JSON.parse(item.json.rawData);
return { json: { success: true, data: parsed } };
} catch (error) {
return { json: { success: false, error: error.message } };
}
});
Webhook Data Access
CRITICAL: In Code nodes, webhook data is under .body:
const message = $input.first().json.message;
const message = $input.first().json.body.message;
const headers = $input.first().json.headers;
const query = $input.first().json.query;
Date/Time with Luxon
n8n includes Luxon for dates:
const { DateTime } = require('luxon');
const now = DateTime.now();
const date = DateTime.fromISO('2024-01-15');
const formatted = now.toFormat('yyyy-MM-dd HH:mm:ss');
const nextWeek = now.plus({ days: 7 });
const yesterday = now.minus({ days: 1 });
const isAfter = now > date;
const diff = now.diff(date, 'days').days;
Binary Data
Access Binary
const items = $input.all();
for (const item of items) {
if (item.binary?.data) {
const buffer = await item.binary.data.toBuffer();
const base64 = buffer.toString('base64');
}
}
Create Binary
const data = { key: 'value' };
const jsonString = JSON.stringify(data, null, 2);
const buffer = Buffer.from(jsonString);
return [{
json: { fileName: 'data.json' },
binary: {
data: await this.helpers.prepareBinaryData(buffer, 'data.json', 'application/json')
}
}];
Common Mistakes
1. Wrong Return Format
return { name: 'John' };
return [{ json: { name: 'John' } }];
2. Not Returning All Items
const item = $input.first();
return [{ json: item.json }];
return $input.all().map(item => ({ json: item.json }));
3. Accessing Wrong Data Level
const data = items[0].data;
const data = items[0].json;
4. Missing await for Async
const response = fetch(url);
const response = await fetch(url);
const data = await response.json();
Available Libraries
Built-in libraries available in Code node:
luxon - Date/time handling
lodash - Utility functions
crypto - Cryptographic functions
const { DateTime } = require('luxon');
const _ = require('lodash');
const crypto = require('crypto');
const grouped = _.groupBy(items, 'category');
const hash = crypto.createHash('sha256').update(data).digest('hex');
Best Practices
- Always return array of
{ json: {...} } objects
- Use
try/catch for error-prone operations
- Access webhook data via
.body
- Use Luxon for dates, not raw Date()
- Validate input data before processing
- Log sparingly - console.log works but adds overhead
Quick Reference
| Need | Code |
|---|
| All items | $input.all() |
| First item | $input.first() |
| Current item | $input.item (each mode) |
| Item JSON | item.json |
| Webhook body | item.json.body |
| Other node | $node["Name"].first().json |
| Env var | $env.VAR_NAME |
| Return item | { json: {...} } |
| Return many | [{ json: {...} }, ...] |
Based on n8n-skills by Romuald Członkowski • Adapted for Moltbot by fazer.ai
Source: fazer-ai/moltbot-skill-n8n — distributed by TomeVault.