n8n code nodes official
Use when the user reaches for a Code node, mentions writing JavaScript or Python in n8n, or any custom logic comes up in workflow design. Triggers on "Code node", "Code", "JavaScript", "Python", "custom logic", "transform data", "$input", "$json transformation", "loop in code", "write a function", or any time the obvious answer seems to be "just put it in code.
By- name:
- n8n-code-nodes-official
- description:
- Use when the user reaches for a Code node, mentions writing JavaScript or Python in n8n, or any custom logic comes up in workflow design. Triggers on "Code node", "Code", "JavaScript", "Python", "custom logic", "transform data", "$input", "$json transformation", "loop in code", "write a function", or any time the obvious answer seems to be "just put it in code.
n8n Code Nodes
The Code node is powerful and often the wrong tool. The n8n equivalent of dropping into raw SQL when an ORM would do: real cases exist, but the moment a Code node handles logic an expression could, the workflow is harder to read, debug, and maintain. There's also a real perf gap: Code runs in a sandboxed JS runtime, expressions and Edit Fields run in-process, and the per-invocation overhead can be hundreds of times higher in Code (anecdotally ~2ms vs ~600ms for equivalent logic). For hot paths and large item counts, that compounds.
Strong defaults
Code node is a last resort. Decision order: expression (
{{...}}) → arrow function inside Edit Fields → Code node. The first two paths cover most "transform this data" tasks. Code earns its place for multi-source aggregation, external libraries, and a few specific patterns documented below.Default to JavaScript. Write JS unless the user explicitly asked for Python ("use Python here," "I'm a Python shop," pasted Python code). Everywhere else in n8n (expressions, Edit Fields) is JS, JS has a curated library allowlist (
lodash,crypto,luxon).
Decision tree
Need custom logic?
├── Is it a transformation of one or two fields?
│ └── Expression: {{ $json.foo.toUpperCase() }} or {{ $json.items.map(item => item.name).join(', ') }}
│ Most "just transform this" cases land here.
│
├── Is it multi-line, but pure data shaping (map, filter, reduce, conditional)?
│ └── Edit Fields with arrow function expression. See references/ARROW_FUNCTIONS_IN_EDIT_FIELDS.md
│
├── Does it need full statements, multiple data sources, or external libs?
│ ├── Are you SURE the above two don't work?
│ │ └── Re-read the parent. The bar is high.
│ └── Yes, genuinely needs it
│ └── Code node. See references/JAVASCRIPT_PATTERNS.md
│
└── Is it actually two separate transformations stitched together?
└── Use two nodes (Edit Fields → Edit Fields, or Edit Fields → IF). Composability beats one big Code block.
For the full decision logic with examples for each branch, see references/DECISION_TREE.md.
What expressions can do that people forget
Common reaches-for-Code-node that should be expressions:
// ❌ Code node
return { name: $input.first().json.name.toUpperCase() }
// ✅ Expression in Edit Fields, "name" field
{{ $json.name.toUpperCase() }}
// ❌ Code node
const items = $input.first().json.items
return { tags: items.map(item => item.tag).filter(tag => tag).join(', ') }
// ✅ Expression
{{ $json.items.map(item => item.tag).filter(tag => tag).join(', ') }}
// ❌ Code node
const date = new Date($input.first().json.created_at)
return { formatted: date.toISOString().slice(0, 10) }
// ✅ Expression with n8n's date extension
{{ $json.created_at.toDateTime().format('yyyy-MM-dd') }}
For more on what expressions can express, see the n8n-expressions-official skill.
What arrow-functions-in-Edit-Fields can do
Edit Fields assigns field values via expression. Inline arrow functions get you most multi-line logic without the Code node:
// In Edit Fields, "summary" field:
{{ (() => {
const items = $json.items
const total = items.reduce((sum, item) => sum + item.price, 0)
const tax = total * 0.08
return `Total: $${(total + tax).toFixed(2)}`
})() }}
Right tool for "logic slightly too gnarly for a one-liner." See references/ARROW_FUNCTIONS_IN_EDIT_FIELDS.md for patterns and formatting.
When the Code node IS the right answer
Real uses exist. Bar is high, not "never." The cases below are legitimate. Build with code without apologizing.
Multi-source aggregation across the whole dataset
When a node needs to:
- Read from multiple upstream nodes simultaneously (e.g.,
$('Source A').all(),$('Source B').all(),$('Source C').first().json). - Compute statistics or transformations across all items at once (not per-item).
- Apply multi-step logic with intermediate data structures (lookup maps, accumulators, ratios).
Most common valid case. Examples:
- Analytics rollups: per-group averages, percentile scoring, normalization across categories.
- Building lookup tables from one source and joining against rows from another.
- Computing offsets/ratios across two reference datasets, then applying to a third.
// Real-world shape: aggregate test results from one source,
// model metadata from another, category mapping from a third,
// and produce per-model-per-category averages.
const testResults = $('Get Test Results').all().map(item => item.json)
const models = $('Get Models').all().map(item => item.json)
const categoryMap = $('Get Category Map').first().json.testCategoryMap
const categoryByTestId = Object.fromEntries(
categoryMap.map(mapping => [mapping.testId, mapping.category])
)
const result = models.map(model => {
const modelTests = testResults.filter(test => test.modelId === model.id)
const stats = modelTests.reduce((acc, test) => {
const cat = categoryByTestId[test.testId]
if (!cat) return acc
acc[cat] ??= { scored: 0, available: 0, count: 0 }
acc[cat].scored += test.pointsScored ?? 0
acc[cat].available += test.pointsAvailable ?? 0
acc[cat].count += 1
return acc
}, {})
const averages = Object.fromEntries(
Object.entries(stats).map(([category, stat]) => [
category,
{ avg: stat.available > 0 ? stat.scored / stat.available : 0, n: stat.count }
])
)
return { modelId: model.id, modelName: model.modelName, ...averages }
})
return result.map(json => ({ json }))
Technically expressions can reach across items via $('Node Name').all() and reduce inline, but for anything with this much shape (joins, group-bys, nested aggregation) the result is a one-line megaexpression that's hard to read and impossible to debug. Use Code.
External libraries
JS Code can require from a curated allowlist (lodash, etc.), but expressions can't.
Always check for a native node first. n8n has more native nodes than people realize. Dropping into Code for something with a native node is a recurring mistake. The next two subsections cover the specific traps.
Cryptographic operations: use the Crypto node, not Code
HMAC, signing, hashing, encryption: n8n has a native Crypto node (n8n-nodes-base.crypto). Use it. It handles SHA256, MD5, HMAC, encrypt/decrypt, and random generation, all without writing JavaScript.
// WRONG (recurring AI slip):
const crypto = require('crypto')
const hash = crypto.createHash('sha256').update(buf).digest('hex').slice(0, 12)
// RIGHT: configure the Crypto node with operation: 'hash', type: 'SHA256'
// then read $('Hash').item.json.<output> downstream.
The Code-with-require('crypto') pattern is one of the most common false positives for "this needs a Code node." It doesn't. The Crypto node covers it.
Hashing binary, not strings
Don't reach for Code just because you need to hash binary (a PDF, an image, a file buffer). The Crypto node has a binaryPropertyName parameter. Point it at the binary slot key and it hashes the buffer directly. You don't need this.helpers.getBinaryDataBuffer(...) in user code.
// WRONG (recurring AI slip with binary):
const crypto = require('crypto')
const buf = await this.helpers.getBinaryDataBuffer($itemIndex, 'data')
const hash = crypto.createHash('sha256').update(buf).digest('hex')
// RIGHT: Crypto node configured to hash binaryPropertyName='data', SHA256.
// Then $('Crypto').item.json.<output> has the hash; chain a Set node for any field shaping.
The remaining valid Code-for-crypto case: a non-standard signing scheme that the Crypto node doesn't expose (e.g., a custom AWS-style signature), AND httpCustomAuth credential doesn't fit either. Rare. Justify explicitly.
XML / SOAP / RSS parsing: use the XML node, not Code
n8n has a native XML node (n8n-nodes-base.xml) with parse and stringify operations. It already converts XML to JSON. Once it has, the result is plain JSON and Edit Fields with arrow function expressions handles all the field extraction, array normalization (Array.isArray(...) ? ... : ...), and link-finding (.find()) you'd reach for Code to do.
// WRONG (recurring AI slip):
// XML node already parsed → another Code node to extract a few fields:
const entry = $('Parse XML').item.json.feed.entry
const firstEntry = Array.isArray(entry) ? entry[0] : entry
return { json: { title: firstEntry.title, url: firstEntry.link.find(link => link.type === 'pdf').href } }
// RIGHT: Edit Fields with arrow function expressions:
// title: ={{ (() => { const entry = $('Parse XML').item.json.feed.entry; return Array.isArray(entry) ? entry[0].title : entry.title; })() }}
// pdfUrl: ={{ $('Parse XML').item.json.feed.entry.link.find(link => link.type === 'pdf')?.href }}
If the field-extraction logic is genuinely too gnarly for inline expressions even with multi-line arrow functions, the next stop is Edit Fields with a single multi-line arrow function, NOT a Code node. See references/ARROW_FUNCTIONS_IN_EDIT_FIELDS.md.
What these have in common
Valid cases are about scope: whole-dataset, multiple sources, or stateful constructs single-item tools can't reach. Invalid cases: Code doing what an expression could, OR what a native node already does.
Quick tests:
- "Could I describe this Code node's job as 'take this one item and...'?" If yes, wrong tool.
- "Is there a native node for this?" Search via
search_nodesfirst. Crypto, XML, JSON parsing, date math (Luxon), HTTP calls, file I/O, regex matching: all have native nodes or expression-level support.
JavaScript Code node specifics
Two modes:
- Run Once for All Items (default, use this): runs once with
$input.all(). If you need per-item logic, justfor (const item of $input.all())inside. This is the standard shape and almost always what you want. - Run Once for Each Item: runs once per item with
$input.first()(or$input.item).
Common shape:
// Run Once for All Items
const items = $input.all()
const totals = items.map(item => ({
...item.json,
total: item.json.qty * item.json.price,
}))
return totals.map(json => ({ json }))
The return must be an array of { json: ... } objects (or { json: ..., binary: ... }), not raw JSON.
For binary handling, error patterns, and Code-node-only bugs, see references/JAVASCRIPT_PATTERNS.md.
Reference files
| File | Read when |
|---|---|
references/DECISION_TREE.md |
You're tempted to use a Code node and want to verify the simpler paths really don't work |
references/ARROW_FUNCTIONS_IN_EDIT_FIELDS.md |
The transformation is multi-line but pure data shaping |
references/JAVASCRIPT_PATTERNS.md |
Code node is genuinely needed and JS is the language |
Anti-patterns
| Anti-pattern | What goes wrong | Fix |
|---|---|---|
Code node doing return { x: $input.first().json.x.toUpperCase() } |
Whole node for one expression | Replace with an Edit Fields expression |
| Code node building HTML strings for an email body | The Email node's body field accepts expressions | Inline the expression into the email node |
Code node using new Date() for date formatting |
Loses to Luxon's clarity | Use Luxon in expression. See n8n-expressions-official |
| Set node + Code node combo (Set builds inputs, Code transforms) | Two nodes for what should be one Edit Fields | Collapse into one Edit Fields with arrow function |
| Pasting credentials/tokens into Code node text | Same leak as text fields | Use credentials, not Code node |
Open this reference as its own page
Arrow functions inside Edit Fields
This pattern handles "logic too gnarly for one line, but just data shaping" without a Code node. An immediately-invoked arrow function inside an Edit Fields expression.
The workhorse pattern for n8n custom logic.
The shape
In an Edit Fields node, set a field's value to:
{{ (() => {
// multi-line logic here
const x = $json.someField
const y = doSomething(x)
return y
})() }}
Breakdown:
{{ ... }}: n8n expression delimiter.(() => { ... })(): arrow function defined and immediately invoked.- Inside: any JS function body.
return: the field's value.
What you can do inside
Pretty much anything in plain JS:
- Multiple
const/let. if/else,switch.for/while(use sparingly, sincemap/filter/reduceis usually cleaner).try/catch.- Inline regex.
- Native JS stdlib:
Math,JSON,String,Array,Object,Number,Map,Set. Prefer Luxon overDate. - Luxon (
DateTime,Interval,Duration).
What you can't do:
require()external libs: Code-node-only.await: expressions are synchronous.
Edit Fields can call $input.all() and $('Other Node').all() though, and that's where this gets powerful: pair it with the Execute Once toggle on the node and you get one-shot cross-item aggregation without a Code node. See "Cross-item aggregation with Execute Once" below.
When to use
Use arrow functions in Edit Fields when the logic is too long for one line, you need intermediate variables, you want comments, or you'd otherwise reach for Code. Works for both per-item logic (default mode) and cross-item aggregation (with Execute Once toggled on, see below).
Code is the right answer when the aggregation logic is too gnarly for an inline arrow function, you need external libs, or you need async.
Performance: this is the other reason to prefer arrow functions
Code nodes run in a sandboxed JS runtime, separate from n8n's main process. Each invocation pays sandbox setup, value marshaling in and out, and isolation overhead. Edit Fields arrow functions run in n8n's expression engine, in-process, with none of that.
The gap is large in practice. Anecdotally, the same logic has been measured at ~2ms in an Edit Fields arrow function vs ~600ms in a Code node. The exact ratio varies with item count and code shape, but the order of magnitude is real.
For most workflows this doesn't matter. The Code node's overhead is a rounding error next to one HTTP call. But when it matters:
- Hot paths. High-frequency triggers (webhook per request, scheduled-every-minute, chat messages on a busy channel).
- Large item counts. Per-item Code execution at 600ms × 10000 items adds up fast, even when each call is "instant" by human standards.
- Latency-sensitive surfaces. Synchronous chat replies, request-response webhooks where total response time is user-visible.
In those cases, cramming what would naturally be a Code node into an Edit Fields arrow function can be worth the readability hit. It's ugly: a 50-line IIFE inside {{...}} is harder to read than a clean Code node. But if profiling shows the Code node is the bottleneck, the win is real and measurable. This is a deliberate trade, not a default.
Examples
Conditional field assembly
{{ (() => {
const status = $json.status
const dueDate = $json.due_date
? DateTime.fromISO($json.due_date)
: null
const isOverdue = dueDate
&& dueDate < DateTime.now()
&& status !== 'completed'
if (isOverdue) {
return `⚠️ OVERDUE: ${$json.title}`
}
if (status === 'in_progress') {
return `🔄 ${$json.title}`
}
if (status === 'completed') {
return `✅ ${$json.title}`
}
return $json.title
})() }}
Branching logic is awkward in a single-line ternary chain and overkill for Code.
Building structured data for an email
{{ (() => {
const items = $json.line_items
const subtotal = items.reduce((sum, item) => sum + item.price * item.qty, 0)
const tax = subtotal * 0.08
const total = subtotal + tax
const rows = items
.map(item => `<tr><td>${item.name}</td><td>${item.qty}</td><td>$${item.price.toFixed(2)}</td></tr>`)
.join('\n')
return `
<h1>Invoice #${$json.invoice_id}</h1>
<table>
<thead><tr><th>Item</th><th>Qty</th><th>Price</th></tr></thead>
<tbody>${rows}</tbody>
</table>
<p>Subtotal: $${subtotal.toFixed(2)}</p>
<p>Tax: $${tax.toFixed(2)}</p>
<p><strong>Total: $${total.toFixed(2)}</strong></p>
`
})() }}
Historically gets written in a Code node and read into an email node. The arrow-function-in-Edit-Fields version keeps it in one place. The email body is in the Edit Fields parameter, not in some upstream Code output.
Parsing freeform user input
{{ (() => {
const text = $json.user_message.toLowerCase()
// Detect intent from common phrasings
const wantsHelp = /\b(help|stuck|how do i)\b/.test(text)
const wantsCancel = /\b(cancel|unsubscribe|stop)\b/.test(text)
const wantsContact = /\b(contact|reach|talk to)\b/.test(text)
if (wantsCancel) return 'cancel'
if (wantsHelp) return 'help'
if (wantsContact) return 'contact'
return 'unknown'
})() }}
Sanitizing input
{{ (() => {
let title = $json.title
title = title.trim()
title = title.replace(/\s+/g, ' ') // collapse whitespace
title = title.replace(/[^\w\s\-.]/g, '') // strip non-alphanumeric (keep dash and dot)
title = title.slice(0, 100) // cap length
return title
})() }}
Formatting rules
Past ~5 lines, formatting matters. Indent generously, comment intent.
{{ (() => {
// Compute stripe-style amount in cents from dollar amount
const dollars = parseFloat($json.amount)
if (isNaN(dollars) || dollars < 0) {
return null
}
const cents = Math.round(dollars * 100)
// Cap at Stripe's max (per their docs)
return Math.min(cents, 99999999)
})() }}
Aim for 4-space indents inside the function. Comments above non-obvious blocks. People read this six months from now.
For broader rules, see the n8n-expressions-official skill.
Common mistakes
Forgetting to invoke the function
// DON'T: defines but doesn't call
{{ () => {
return $json.foo.toUpperCase()
} }}
The result of this expression is the function itself, not its return value. Always close with () to invoke:
{{ (() => {
return $json.foo.toUpperCase()
})() }}
Returning nothing
{{ (() => {
const x = $json.foo
x.toUpperCase() // ← no return
})() }}
The expression evaluates to undefined. Always end with an explicit return.
Cross-item aggregation with Execute Once
By default Edit Fields runs once per input item, so calling $input.all() inside an arrow function re-evaluates the same array N times. Toggle Execute Once on the node and the expression runs once total, producing one output item. That combination is the lightweight alternative to a Code node for aggregations:
// Execute Once enabled on the Edit Fields node
{{ (() => {
const items = $input.all().map(item => item.json)
const total = items.reduce((sum, item) => sum + item.amount, 0)
return `Processed ${items.length} items, total $${total.toFixed(2)}`
})() }}
The same shape works for $('Other Node').all() when you want to aggregate across an upstream node specifically. Reach for a Code node only when the aggregation logic is too gnarly for an inline arrow function (joins, group-bys, multiple intermediate structures).
Without Execute Once, the expression still resolves, you just pay the cost N times and produce N identical output items, which is almost never what you want.
Awaiting
// DON'T
{{ (async () => {
const data = await fetch(...) // expressions are synchronous
})() }}
If you need async work, that's a separate node (HTTP Request, etc.), not an arrow function.
When this gets too big
Past ~30 lines, ask:
- Could this be split into multiple Edit Fields steps?
- Is this genuinely a Code case? (See
DECISION_TREE.md.) - Is it domain-specific enough to be a sub-workflow? (See
n8n-subworkflows-official.)
Great for "a bit too gnarly for one line." Not great for "I'm writing a small program."
Open this reference as its own page
Decision tree
The bar for using a Code node is high. This file walks through verifying that simpler alternatives (expression, Edit Fields arrow function) don't work.
Stage 1: try an expression
For any single-field transform, ask: can this fit in {{...}}?
Expressions express:
- Property access (
$json.foo.bar) - Method chains (
$json.items.filter(...).map(...).join(...)) - Ternary conditionals
- Arithmetic and string interpolation
- Date math via Luxon
- Native JS methods on arrays/strings/objects/numbers
If it fits one line, even a long one, do it as an expression. Multi-line indented form is supported. See the n8n-expressions-official skill.
Test: can you describe it as "take A and produce B" without intermediate variables? If yes, expression.
// Expression: "take items, return joined names"
{{ $json.items.map(item => item.name).join(', ') }}
// Expression: "take created_at, return YYYY-MM-DD"
{{ DateTime.fromISO($json.created_at).toFormat('yyyy-MM-dd') }}
// Expression: "take items, return their total"
{{ $json.items.reduce((sum, item) => sum + item.price, 0) }}
Stage 2: try Edit Fields with an arrow function
When the transform needs intermediate variables, multi-step logic, or doesn't fit one line, use Edit Fields with an inline arrow function.
Pattern: an immediately-invoked arrow function inside the expression.
{{ (() => {
const items = $json.items
const total = items.reduce((sum, item) => sum + item.price, 0)
const tax = total * 0.08
return `Total: $${(total + tax).toFixed(2)}`
})() }}
This buys you:
- Multiple statements
- Local variables
- Early returns
- Comments
What you give up vs. a Code node:
- No external libraries
- No
requires - No access to
$input.all()(you have$jsonfor the current item, not all items at once)
For more, see ARROW_FUNCTIONS_IN_EDIT_FIELDS.md.
Test: does the logic operate on a single input item ($json)? If yes, Edit Fields. If you need to combine items, see Stage 3.
Stage 3: justify the Code node
Stages 1 and 2 are ruled out. Remaining valid reasons:
Reason A: External libraries
JS Code supports a curated allowlist (lodash, crypto, luxon). If you genuinely need lodash.groupBy or one of the others, Code is necessary. No HTTP client is bundled, use the HTTP Request node for any outbound calls.
Counter-question: do you actually need lodash? Modern JS has Array.prototype.reduce and Object.entries.
Reason B: Multi-source aggregation across the whole dataset
Most common valid case. When a node needs to:
- Read from multiple upstream nodes simultaneously.
- Compute statistics or transformations across all items at once.
- Apply multi-step logic with intermediate data structures.
Code, full stop. Don't split across many Edit Fields.
Splitting an analytics rollup into 10+ smaller nodes is harder to read, debug, and iterate than one 80-line Code node with clear sections.
But: ask if part can be a built-in (Aggregate, Summarize, Sort, Group). Check via search_nodes. If a built-in covers half, do that half there.
Reason B-adjacent: Statistical operations across many items
Median, percentile, ratio-of-ratios, normalized scores: anything needing all items to compute an answer for any one. Single-item tools can't express this.
Reason C: Crypto operations
HMAC signing, JWT verification, custom encryption. JS has require('crypto'). Python has hashlib and hmac.
Counter-question: is this for auth? See n8n-credentials-and-security-official. httpCustomAuth may handle it without code.
Reason D: User has existing JS/Python they want to drop in
Worth pushing back on. n8n workflows are visual, and dropping a 200-line script defeats most of the value. Options:
- Refactor into multiple nodes.
- Run as a separate service called via HTTP Request.
- Decide this case justifies one Code node and document why in the description.
When the user insists on a Code node
Their call. Build it, but:
- Comment in the Code node explaining why simpler tools weren't used.
- Keep small.
- Run the workflow and verify outputs before publishing.
Examples by category
"Format a date"
- One format: expression (Luxon).
- Multiple formats: Edit Fields with arrow function.
- Code node: only if you're computing dates from non-trivial sources (e.g., parsing freeform user input with intent disambiguation).
"Filter items by criteria"
- Simple: expression on the previous node's output, or use the IF node.
- Conditional with multiple criteria: Edit Fields arrow function.
- Code node: only if criteria depend on aggregate stats across all input items.
"Build an email body"
- Static template with field substitution: expression in the email node's body field.
- Conditional sections: arrow function in the email body field.
- Code node: never. Building strings is the most over-Code'd pattern in n8n.
"Transform API response into target shape"
- One-to-one field mapping: Edit Fields with expressions.
- Map/filter/reduce on arrays in the response: still expressions.
- Combining responses from multiple HTTP calls: Merge node + Edit Fields. Code node only if the merge logic is genuinely complex.
"Validate input data"
- Use the IF node or built-in validation nodes (
schema validationif available). - Edit Fields with arrow function for "compute a
validboolean." - Code node: rare, and usually a sign that validation should happen upstream of n8n.
The honest answer
Code feels productive because writing JS is what you know. But the workflow gets read by someone (maybe future-you) who has to understand each node at a glance, modify one piece without breaking others, and debug from runtime errors.
Visual nodes with descriptive names beat a Code block on every one. 30 seconds saved now costs hours later.
When in doubt: not a Code node.
Open this reference as its own page
JavaScript Code node patterns
Once DECISION_TREE.md confirms Code is necessary, this covers patterns and gotchas.
Run modes
Two execution modes. Default to Run Once for All Items. It's the standard shape and almost always what you want, even when the work is per-item: just for (const item of $input.all()) or .map() inside.
Run Once for All Items (default, use this)
Runs once with all items as $input.all(). Per-item logic just goes inside the loop.
const items = $input.all()
const totals = items.map(item => ({
...item.json,
total: item.json.qty * item.json.price,
}))
return totals.map(json => ({ json }))
Run Once for Each Item
Runs once per input item. $input.first() (or $input.item) is the current item.
const item = $input.first().json
return [{ json: { ...item, total: item.qty * item.price } }]
Picking the mode
| Need | Mode |
|---|---|
| Anything aggregate / reduce across items | Run for All |
| Combine items conditionally | Run for All |
| Per-item transform | Run for All with a loop inside (Edit Fields is usually even better) |
| Per-item with explicit error isolation per item | Run for Each, paired with continueOnFail |
| Fan-out: turn 1 input item into N output items | Run for All, return the expanded array |
Return shape
The Code node must return an array of { json: ... } objects. Variations:
// Single output item
return [{ json: { foo: 'bar' } }]
// Multiple output items
return [
{ json: { id: 1 } },
{ json: { id: 2 } },
]
// Item with binary
return [{
json: { name: 'report.pdf' },
binary: { data: { /* binary data */ } }
}]
// Empty output (skip downstream)
return []
Common mistake: returning the raw object instead of the array-of-{json} shape.
// ❌ DON'T
return { foo: 'bar' }
// ✅ DO
return [{ json: { foo: 'bar' } }]
Available libraries
Curated list of pre-imported / requireable libraries. The set evolves. Reliably present:
crypto: Node's crypto module.lodash(sometimes as_):groupBy,chunk,keyByare still handy.moment: deprecated. Prefer Luxon, available globally.
No HTTP client (axios, node-fetch, etc.) is bundled. Use the HTTP Request node for any outbound HTTP, that's a hard line.
Hard list. You cannot install new packages.
Handling binary data
Binary lives in item.binary[<key>], separately from item.json. Common patterns:
// Pass binary through unchanged
const items = $input.all()
return items.map(item => ({
json: { ...item.json, processed: true },
binary: item.binary,
}))
// Read binary as buffer (e.g., for hashing)
const item = $input.first()
const buffer = await this.helpers.getBinaryDataBuffer(0, 'data')
const hash = crypto.createHash('sha256').update(buffer).digest('hex')
return [{ json: { hash }, binary: item.binary }]
See n8n-binary-and-data-official for binary patterns. Code nodes are one of several ways to handle binary, often not the best.
Common patterns that justify Code
Aggregation that built-in nodes don't cover
// Compute median across input items
const values = $input.all().map(item => item.json.value).sort((valueA, valueB) => valueA - valueB)
const mid = Math.floor(values.length / 2)
const median = values.length % 2
? values[mid]
: (values[mid - 1] + values[mid]) / 2
return [{ json: { median, count: values.length } }]
(But: check search_nodes for a built-in aggregation node first. If one exists, use it.)
HMAC signing
const crypto = require('crypto')
const item = $input.first().json
const body = JSON.stringify(item.payload)
const signature = crypto
.createHmac('sha256', item.secret)
.update(body)
.digest('hex')
return [{ json: { ...item, signature } }]
(But: see n8n-credentials-and-security-official's CUSTOM_CREDENTIALS.md. The secret should come from a credential, not be passed in input data.)
Things to avoid
console.log for "debugging"
Goes to instance logs the user may not have access to. Use test_workflow and get_workflow_execution.
To surface debug info downstream:
return [{ json: { ...result, _debug: { stepCount: 3, intermediate } } }]
Strip _debug in a downstream Edit Fields before publishing.
Long-running synchronous loops
A for loop doing HTTP calls or thousands of synchronous items blocks execution and may time out.
Better:
- HTTP calls: HTTP Request node +
SplitInBatches. - Many items: smaller batches + Aggregate to combine.
Error swallowing
// DON'T
try {
return [{ json: doRiskyThing() }]
} catch (error) {
return [{ json: { error: error.message } }]
}
Returning error as data hides it: workflow continues as if all is well, downstream gets error-shaped data.
Better: let Code throw, set onError: 'continueErrorOutput' and wire output(1). See n8n-error-handling-official.
Re-implementing built-in functionality
If you're writing JS for HTTP calls, email sending, file uploads, or date math, use the corresponding native node or Luxon in expressions.
Performance
Code runs in a sandboxed JS runtime, separate from n8n's main process. Each invocation pays sandbox setup, value marshaling, and isolation overhead. The same logic in an Edit Fields arrow function (which runs in-process via the expression engine) can be hundreds of times faster, anecdotally ~2ms vs ~600ms for the same code.
For most workflows the overhead is a rounding error next to one HTTP call. When it matters (hot paths, large item counts, latency-sensitive webhooks), see the performance section in ARROW_FUNCTIONS_IN_EDIT_FIELDS.md. Cramming code-node-grade logic into an inline arrow function is ugly but can be the right call.
99% of the time the bottleneck is upstream (HTTP call, DB query). If genuinely slow, profile via get_workflow_execution first.
Testing
Always run test_workflow after writing a Code node. Most error-prone single-node category in n8n: type errors, return-shape mistakes, library assumptions. Test before publish.
More in this playbook
Safe to turn on
Use this skill when an agent or person is about to create, change or enable an automation inside someone else's account or a shared environment: "create this workflow", "build it in the customer's account", "turn it on", "go live", "deploy this automation". Produces a proposal the human approves, an automation created in the off state, and a short list of what only the human can finish.
Workflow buildingMITn8n agents
Design n8n AI agents the right way. Use when building or editing any @n8n/n8n-nodes-langchain.* AI node — an AI Agent, LLM chain, Text Classifier, or Information Extractor — and whenever the user mentions AI agents, LLM with tools, tool calling, $fromAI, system prompts, agent memory, sessionId, structured/JSON output, output parser, RAG, vector store, a chat assistant/bot, or human-in-the-loop review. Covers Agent-vs-chain-vs-classifier choice, the model/memory/tools/outputParser slots, tool names/descriptions as prompt, structured output with autoFix, memory, RAG, human review, and chat topologies.
Workflow buildingMITn8n agents
Design n8n AI agents the right way. Use when building or editing any @n8n/n8n-nodes-langchain.* AI node — an AI Agent, LLM chain, Text Classifier, or Information Extractor — and whenever the user mentions AI agents, LLM with tools, tool calling, $fromAI, system prompts, agent memory, sessionId, structured/JSON output, output parser, RAG, vector store, a chat assistant/bot, or human-in-the-loop review. Covers Agent-vs-chain-vs-classifier choice, the model/memory/tools/outputParser slots, tool names/descriptions as prompt, structured output with autoFix, memory, RAG, human review, and chat topologies.


