M
MJK.Supplies
Home / n8n / n8n Code Node…
n8n

n8n Code Node

n8n's Code node is what separates it from purely no-code platforms. When visual nodes reach their limits — complex data transformations, custom calculations, dynamic logic — the Code node lets you write JavaScript or Python to handle it. This guide covers how to use the Code node effectively, from basic data manipulation to complex transformations.

M
MJK Supplies · Jan 17, 2026 · 3 min read
ShareXinf↗
n8n Code Node

When to Use the Code Node

The Code node is appropriate when:

Complex data transformation: You need to reshape data in ways that visual nodes can't express — merging arrays from multiple sources, creating nested structures, normalising inconsistent data formats.

Custom calculations: Math operations beyond what expression nodes support — running totals, statistical calculations, date arithmetic with business logic.

Dynamic logic: Logic that depends on the data itself — if the array has more than 10 items, process it differently; iterate over a dynamic number of items; group data by a calculated key.

Parsing custom formats: Extracting data from non-standard formats — custom string formats, legacy data structures, inconsistently formatted imports.

AI response processing: Cleaning and validating AI model outputs before passing to downstream nodes.

Code Node Basics

The Code node receives data from the previous node and returns transformed data to the next node.

Input: $input.all() returns all items from the previous node. $input.first() returns the first item. Each item has a json property containing the data.

Output: Return an array of objects, each with a json property:

return items.map(item => { return { json: { ...item.json, newField: 'new value' } }; });

Access previous nodes: $node['Node Name'].json gives you access to any previous node's output.

Common Code Node Patterns

Add computed fields:

const items = $input.all(); return items.map(item => ({ json: { ...item.json, fullName: `${item.json.firstName} ${item.json.lastName}`, score: item.json.revenue > 100000 ? 'high' : 'medium' } }));

Filter items:

const items = $input.all(); return items.filter(item => item.json.score > 70).map(item => ({ json: item.json }));

Aggregate data:

const items = $input.all(); const total = items.reduce((sum, item) => sum + item.json.amount, 0); const avg = total / items.length; return [{ json: { total, average: avg, count: items.length } }];

Group by field:

const items = $input.all(); const grouped = {}; items.forEach(item => { const key = item.json.category; if (!grouped[key]) grouped[key] = []; grouped[key].push(item.json); }); return Object.entries(grouped).map(([category, entries]) => ({ json: { category, entries, count: entries.length } }));

Parse AI JSON output:

const aiResponse = $input.first().json.response; // Claude's raw text response try { const parsed = JSON.parse(aiResponse); return [{ json: { ...parsed, parse_success: true } }]; } catch (e) { return [{ json: { parse_success: false, raw_response: aiResponse, error: e.message }}]; }

Date manipulation:

const items = $input.all(); return items.map(item => { const created = new Date(item.json.createdAt); const now = new Date(); const daysSinceCreation = Math.floor((now - created) / (1000 * 60 * 60 * 24)); return { json: { ...item.json, daysSinceCreation, isOlderThan30Days: daysSinceCreation > 30 } }; });

Async Operations in Code Nodes

For operations that require async/await (HTTP calls, delays):

// Note: n8n handles the Promise automatically const response = await $http.get('https://api.example.com/data/' + $input.first().json.id); return [{ json: response.data }];

Using $http within a Code node allows HTTP calls without a separate HTTP Request node — useful for inline data fetching during complex transformations.

Python Code Node

n8n also supports Python in the Code node (select Python from the language dropdown). Python is useful for:

  • Data analysis with pandas-style operations
  • Mathematical computations
  • Engineers more comfortable with Python than JavaScript

Python access pattern:

items = _input.all() return [{"json": {"processed": True, "count": len(items)}}]

Recommended Tools

  • n8n — Platform with Code node capability
  • Claude API — AI output that Code nodes often parse and transform
  • n8n Community — Examples and solutions for Code node patterns
  • Airtable — Destination for transformed data
“The Code node is n8n's superpower. It transforms n8n from a visual automation tool into a complete business logic platform. Master it and the only limit is what you can code.”
#n8n#code#node

Related articles

MJK Supplies · Automation Services

Want this built for you?

We design and ship custom AI agents and automation systems for teams that want results, not a backlog. Book a free 30-minute consult — no commitment, no pitch deck.