JavaScript Code Node
Expert guidance for writing JavaScript code in n8n Code nodes.
JavaScript is recommended for 95% of n8n Code use cases — full
$helpers, Luxon DateTime, no library limitations.
When to use
- Writing or reviewing a JavaScript Code node in n8n.
- Using
$input / $json / $node syntax.
- Making HTTP requests with
$helpers.httpRequest.
- Date/time work with
DateTime (Luxon).
- Querying JSON with
$jmespath.
- Choosing between Code node modes (All Items vs Each Item).
- Debugging Code node errors (return shape, webhook nesting, undefined fields).
Required input contract
Before writing or reviewing a JavaScript Code node, identify:
- Mode — "Run Once for All Items" (default, 95% of cases) vs "Run Once for Each Item".
- Upstream node(s) — which provides the input (webhook, HTTP, manual, prior Code node).
- Required output cardinality — single, list, empty, or filtered.
- External calls — does this node need
$helpers.httpRequest?
- Reason for Code node — not solvable by Set / Filter / IF / HTTP Request nodes alone.
n8n JavaScript Code node constraints
These constraints apply to every JavaScript Code node and must always be respected.
- Return shape: every code path returns an array of objects each with
a
json key. Single returns wrapped in array. Empty result is return [].
- Webhook data nests under
.body. Use $json.body?.<field> or
$input.first().json.body.
- Optional chaining + nullish coalescing for nullable fields:
$json.body?.name ?? "".
- No
{{ }} expression syntax inside the Code node body. Code nodes
execute pure JavaScript — use template literals or direct access.
$helpers.httpRequest always inside try/catch. Awaitable; throws on failure.
DateTime time zones pinned explicitly when crossing zones — never
rely on the server default.
- Do not mutate
item.json in place — construct new objects
({ json: { ...item.json, extra: v } }).
- Do not return
$input.all() raw — map first to produce a fresh
{ json } shape.
- Credentials live in n8n credential storage, never in source.
Workflow (compact)
- Mode: All Items (default) vs Each Item.
- Read:
$input.all() / .first() / .item / $node["..."].json.
- Transform: array methods (
map / filter / reduce).
- Return:
[{ json: {...} }, ...] on every code path.
- Validate: walk the gates (below).
Full workflow + mode examples + return-format matrix:
references/javascript-code-workflow.md.
Decision logic
Mode selection
| Mode |
When |
Data access |
| Run Once for All Items (default, 95%) |
Aggregation, filtering, batch, API calls with all data |
$input.all() / items |
| Run Once for Each Item |
Item-specific logic, independent operations |
$input.item / $item |
Data access
| Accessor |
When |
$input.all() |
Arrays, batches, aggregations |
$input.first() |
Single objects, API responses |
$input.item |
Each-Item mode only |
$node["Name"].json |
Reference a non-immediate upstream node |
When to use the Code node vs another node
| Situation |
Use |
| Complex multi-step transformations |
Code node |
| Custom calculations / business logic |
Code node |
| API response parsing with complex structure |
Code node |
| Simple field mapping |
Set node |
| Basic filtering |
Filter node |
| Conditional routing |
IF / Switch node |
| HTTP only, no transform |
HTTP Request node |
| Need HTTP + custom logic in one node |
Code node (JavaScript, with $helpers.httpRequest) |
Minimal critical examples
Quick Start
const items = $input.all();
return items.map(item => ({
json: {
...item.json,
processed: true,
timestamp: new Date().toISOString(),
},
}));
Webhook field access
const name = $json.body?.name ?? "";
return [{ json: { name: name.trim() } }];
HTTP from inside the Code node
try {
const res = await $helpers.httpRequest({
method: "GET",
url: "https://api.example.com/items",
});
return res.data.map(it => ({ json: { id: it.id, name: it.name } }));
} catch (err) {
return [{ json: { ok: false, error: err.message } }];
}
Return-format right/wrong
return [{ json: { id: 1 } }]; // RIGHT — single
return [{ json: { id: 1 } }, { json: { id: 2 } }]; // RIGHT — multiple
return []; // RIGHT — empty
return { json: { id: 1 } }; // WRONG — not wrapped
return [{ id: 1 }]; // WRONG — missing "json" key
return $input.all(); // WRONG — raw input
Worked end-to-end examples (webhook, API fetch + merge, group-by,
multi-node combine, regex extract, per-item conditional, date-range filter):
references/examples.md.
Validation gates
Before deploying a JavaScript Code node:
Full top-5 mistakes, best practices, debugging playbook, anti-patterns:
references/validation-troubleshooting-and-antipatterns.md.
Output expectations
When delivering a JavaScript Code node:
- Provide the full code block, ready to paste into the Code node.
- State the mode (All Items / Each Item).
- Note any required upstream nodes.
- Flag any branch that returns
[] and what that means downstream.
- List required credentials if
$helpers.httpRequest is used.
Integration with other skills
- n8n Expression Syntax — expressions use
{{ }} in other nodes; Code nodes use JavaScript directly.
- n8n MCP Tools Expert — find Code node via
search_nodes({query: "code"});
configure via get_node({nodeType: "nodes-base.code"}); validate via
validate_node({nodeType: "nodes-base.code", config: {...}}).
- n8n Node Configuration — mode and language selection are node properties.
- n8n Workflow Patterns — Code nodes in transformation steps; Webhook → Code → API; error handling.
- n8n Validation Expert — interpret validation errors, auto-fix.
- n8n Code Python — when to switch (rare); feature comparison.
Reference map
| Need |
Read |
| Mode selection + runtime + return-format full examples; workflow steps |
references/javascript-code-workflow.md |
| 4 data access patterns, webhook body, 5 production patterns (aggregate / regex / transform / top-N / reduce) |
references/item-and-data-patterns.md |
$helpers.httpRequest (auth, retry, multi-request), DateTime / Luxon, $jmespath, integration decision table |
references/helpers-and-integrations.md |
| Top 5 mistakes, best practices, validation gates, debugging playbook, anti-patterns |
references/validation-troubleshooting-and-antipatterns.md |
| End-to-end worked examples |
references/examples.md |
| Upstream comprehensive depth |
references/common-patterns.md, references/data-access.md, references/error-patterns.md, references/builtin-functions.md |
1---2name: n8n-code-javascript3description: Write JavaScript code in n8n Code nodes. Use when writing JavaScript in n8n, using $input/$json/$node syntax, making HTTP requests with $helpers, working with dates using DateTime, troubleshooting Code node errors, or choosing between Code node modes.4---56# JavaScript Code Node78Expert guidance for writing JavaScript code in n8n Code nodes.9**JavaScript is recommended for 95% of n8n Code use cases** — full10`$helpers`, Luxon DateTime, no library limitations.1112## When to use1314- Writing or reviewing a JavaScript Code node in n8n.15- Using `$input` / `$json` / `$node` syntax.16- Making HTTP requests with `$helpers.httpRequest`.17- Date/time work with `DateTime` (Luxon).18- Querying JSON with `$jmespath`.19- Choosing between Code node modes (All Items vs Each Item).20- Debugging Code node errors (return shape, webhook nesting, undefined fields).2122## Required input contract2324Before writing or reviewing a JavaScript Code node, identify:2526- **Mode** — "Run Once for All Items" (default, 95% of cases) vs "Run Once for Each Item".27- **Upstream node(s)** — which provides the input (webhook, HTTP, manual, prior Code node).28- **Required output cardinality** — single, list, empty, or filtered.29- **External calls** — does this node need `$helpers.httpRequest`?30- **Reason for Code node** — not solvable by Set / Filter / IF / HTTP Request nodes alone.3132## n8n JavaScript Code node constraints3334These constraints apply to every JavaScript Code node and must always be respected.35361. **Return shape**: every code path returns an array of objects each with37 a `json` key. Single returns wrapped in array. Empty result is `return []`.382. **Webhook data nests under `.body`**. Use `$json.body?.<field>` or39 `$input.first().json.body`.403. **Optional chaining + nullish coalescing** for nullable fields:41 `$json.body?.name ?? ""`.424. **No `{{ }}` expression syntax inside the Code node body.** Code nodes43 execute pure JavaScript — use template literals or direct access.445. **`$helpers.httpRequest` always inside `try`/`catch`.** Awaitable; throws on failure.456. **`DateTime` time zones pinned explicitly** when crossing zones — never46 rely on the server default.477. **Do not mutate `item.json` in place** — construct new objects48 (`{ json: { ...item.json, extra: v } }`).498. **Do not return `$input.all()` raw** — map first to produce a fresh50 `{ json }` shape.519. **Credentials live in n8n credential storage**, never in source.5253## Workflow (compact)54551. **Mode**: All Items (default) vs Each Item.562. **Read**: `$input.all()` / `.first()` / `.item` / `$node["..."].json`.573. **Transform**: array methods (`map` / `filter` / `reduce`).584. **Return**: `[{ json: {...} }, ...]` on every code path.595. **Validate**: walk the gates (below).6061Full workflow + mode examples + return-format matrix:62`references/javascript-code-workflow.md`.6364## Decision logic6566### Mode selection6768| Mode | When | Data access |69|------|------|-------------|70| Run Once for All Items (default, 95%) | Aggregation, filtering, batch, API calls with all data | `$input.all()` / `items` |71| Run Once for Each Item | Item-specific logic, independent operations | `$input.item` / `$item` |7273### Data access7475| Accessor | When |76|----------|------|77| `$input.all()` | Arrays, batches, aggregations |78| `$input.first()` | Single objects, API responses |79| `$input.item` | Each-Item mode only |80| `$node["Name"].json` | Reference a non-immediate upstream node |8182### When to use the Code node vs another node8384| Situation | Use |85|-----------|-----|86| Complex multi-step transformations | Code node |87| Custom calculations / business logic | Code node |88| API response parsing with complex structure | Code node |89| Simple field mapping | **Set** node |90| Basic filtering | **Filter** node |91| Conditional routing | **IF** / **Switch** node |92| HTTP only, no transform | **HTTP Request** node |93| Need HTTP + custom logic in one node | Code node (JavaScript, with `$helpers.httpRequest`) |9495## Minimal critical examples9697### Quick Start9899```javascript100const items = $input.all();101return items.map(item => ({102 json: {103 ...item.json,104 processed: true,105 timestamp: new Date().toISOString(),106 },107}));108```109110### Webhook field access111112```javascript113const name = $json.body?.name ?? "";114return [{ json: { name: name.trim() } }];115```116117### HTTP from inside the Code node118119```javascript120try {121 const res = await $helpers.httpRequest({122 method: "GET",123 url: "https://api.example.com/items",124 });125 return res.data.map(it => ({ json: { id: it.id, name: it.name } }));126} catch (err) {127 return [{ json: { ok: false, error: err.message } }];128}129```130131### Return-format right/wrong132133```javascript134return [{ json: { id: 1 } }]; // RIGHT — single135return [{ json: { id: 1 } }, { json: { id: 2 } }]; // RIGHT — multiple136return []; // RIGHT — empty137return { json: { id: 1 } }; // WRONG — not wrapped138return [{ id: 1 }]; // WRONG — missing "json" key139return $input.all(); // WRONG — raw input140```141142Worked end-to-end examples (webhook, API fetch + merge, group-by,143multi-node combine, regex extract, per-item conditional, date-range filter):144`references/examples.md`.145146## Validation gates147148Before deploying a JavaScript Code node:149150- [ ] Code is not empty.151- [ ] Final `return` statement exists.152- [ ] Return shape is `[{ json: {...} }, ...]` on every code path.153- [ ] Data access uses only `$input.all()` / `$input.first()` / `$input.item` /154 `$node["..."].json`.155- [ ] No `{{ }}` expression syntax inside the Code node body.156- [ ] `?.` and `??` used for nullable fields.157- [ ] Webhook data accessed via `$json.body?.<field>`.158- [ ] `try`/`catch` wraps every `$helpers.httpRequest`.159- [ ] Mode is "All Items" unless per-item independence is required.160- [ ] Output consistent across every branch and exception path.161- [ ] `DateTime` time zones pinned explicitly when crossing zones.162163Full top-5 mistakes, best practices, debugging playbook, anti-patterns:164`references/validation-troubleshooting-and-antipatterns.md`.165166## Output expectations167168When delivering a JavaScript Code node:169170- Provide the full code block, ready to paste into the Code node.171- State the mode (All Items / Each Item).172- Note any required upstream nodes.173- Flag any branch that returns `[]` and what that means downstream.174- List required credentials if `$helpers.httpRequest` is used.175176## Integration with other skills177178- **n8n Expression Syntax** — expressions use `{{ }}` in other nodes; Code nodes use JavaScript directly.179- **n8n MCP Tools Expert** — find Code node via `search_nodes({query: "code"})`;180 configure via `get_node({nodeType: "nodes-base.code"})`; validate via181 `validate_node({nodeType: "nodes-base.code", config: {...}})`.182- **n8n Node Configuration** — mode and language selection are node properties.183- **n8n Workflow Patterns** — Code nodes in transformation steps; Webhook → Code → API; error handling.184- **n8n Validation Expert** — interpret validation errors, auto-fix.185- **n8n Code Python** — when to switch (rare); feature comparison.186187## Reference map188189| Need | Read |190|------|------|191| Mode selection + runtime + return-format full examples; workflow steps | `references/javascript-code-workflow.md` |192| 4 data access patterns, webhook body, 5 production patterns (aggregate / regex / transform / top-N / reduce) | `references/item-and-data-patterns.md` |193| `$helpers.httpRequest` (auth, retry, multi-request), DateTime / Luxon, `$jmespath`, integration decision table | `references/helpers-and-integrations.md` |194| Top 5 mistakes, best practices, validation gates, debugging playbook, anti-patterns | `references/validation-troubleshooting-and-antipatterns.md` |195| End-to-end worked examples | `references/examples.md` |196| Upstream comprehensive depth | `references/common-patterns.md`, `references/data-access.md`, `references/error-patterns.md`, `references/builtin-functions.md` |