JavaScript Code Nodes
Expert guidance for writing JavaScript code in n8n Code nodes.Quick Start Template
- Choose “Run Once for All Items” mode (recommended for 95% of use cases)
- Access data via
$input.all(),$input.first(), or$input.item - Must return
[{json: {...}}]format — array of objects with ajsonkey - Webhook data is under
$json.body(not$jsondirectly) - Built-ins available:
$helpers.httpRequest(),DateTime(Luxon),$jmespath()
Mode Selection
- Run Once for All Items (recommended)
- Run Once for Each Item
- Code executes once regardless of input count
- Access data via
$input.all()or theitemsarray - Best for: aggregation, filtering, batch processing, transformations
- Faster for multiple items (single execution)
Data Access Patterns
Return Format Requirements
Built-in Functions
$helpers.httpRequest()
Make HTTP requests from within a Code node:
DateTime (Luxon)
Date and time operations using the Luxon library:
$jmespath()
Query and filter JSON structures:
Top 5 Error Patterns
#1: Empty code or missing return (most common)
#1: Empty code or missing return (most common)
#2: Using n8n expression syntax in code
#2: Using n8n expression syntax in code
#3: Incorrect return wrapper
#3: Incorrect return wrapper
#4: Missing null / undefined checks
#4: Missing null / undefined checks
#5: Webhook body nesting
#5: Webhook body nesting
10 Production-Tested Patterns
1. Data transformation and field mapping
1. Data transformation and field mapping
2. Aggregation and reporting
2. Aggregation and reporting
3. Top-N filtering and ranking
3. Top-N filtering and ranking
4. Multi-source data aggregation
4. Multi-source data aggregation
5. Regex filtering and extraction
5. Regex filtering and extraction
6. HTTP request with error handling
6. HTTP request with error handling
7. Date manipulation with Luxon
7. Date manipulation with Luxon
8. Deduplication
8. Deduplication
9. Data validation and cleaning
9. Data validation and cleaning
10. Combining data from multiple nodes
10. Combining data from multiple nodes
Best Practices
When to Use a Code Node
Pre-Deploy Checklist
- Code is not empty — has meaningful logic
- Return statement exists
- Return format is
[{json: {...}}] - Data access uses
$input.all(),$input.first(), or$input.item - No
{{ }}expressions — using direct JavaScript access - Null/undefined guards with optional chaining (
?.) or defaults - Webhook data accessed via
.bodyif input is from a Webhook node - Mode is “All Items” unless per-item isolation is required
- All code paths return the same structure