Core nodes10 min readUpdated 2026-06-29

n8n Code Node: JavaScript Patterns That Save Hours

Use the n8n Code node to filter, reshape, dedupe, and call libraries. Includes async patterns, npm modules, and pitfalls.

Key takeaways

  • Use 'Run Once for All Items' when you need to aggregate; 'Run Once for Each Item' for per-row transforms.
  • Return $input.all() unchanged at the end if you're only adding fields.
  • Built-ins available: crypto, DateTime (Luxon), $jmespath. No fetch — use the HTTP Request node.
  • Self-hosted lets you allow extra npm modules via NODE_FUNCTION_ALLOW_EXTERNAL.

The Code node is n8n's escape hatch from no-code constraints. A few well-written Code nodes eliminate sprawling chains of Set + IF + Merge. Here are the patterns that come up over and over.

Pattern — dedupe by field

const seen = new Set(); return $input.all().filter(i => { const k = i.json.email; if (seen.has(k)) return false; seen.add(k); return true; });

Pattern — pivot rows to columns

Aggregate by group with reduce, emit one item per group with arrays of children. Eliminates a Merge + Loop chain.

Pattern — HMAC signature verification

const crypto = require('crypto'); const sig = $input.first().json.headers['x-signature']; const body = $input.first().json.body; const expected = crypto.createHmac('sha256', $env.WEBHOOK_SECRET).update(body).digest('hex'); if (!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))) throw new Error('Bad signature'); return $input.all();

When to use Python instead

The Python Code node (self-hosted, beta) is useful when you need numpy, pandas, or specific ML libraries. JavaScript is faster to ship for everything else.

Frequently asked questions

Can I install npm packages for the Code node?
On self-hosted, yes via NODE_FUNCTION_ALLOW_EXTERNAL. On Cloud, no — use the HTTP Request node to call a service instead.
Why does my Code node return only the first item?
You're in 'Run Once for Each Item' mode and returning a single object. Switch modes or wrap in an array.
HomePathTemplatesBlogMy