Skip to content
New: a free website for your business, live in 48 to 72 hoursWorkflow automation on n8n and Claude, built for your businessFixed price, agreed before we start · Live in 5 to 10 business days30-day money-back guarantee on every planProfessional firms · Agencies · E-commerceYou own every workflow, in your own n8nClaude API: your data is not used for trainingHuman approval on every sensitive stepFree automation audit, no obligation
PURIST
30 days
Money-back window
14 h/wk
Modeled time saved
99.97%
Uptime SLA
< 7 days
Deploy time
PURIST AI
Claude Opus 4.7 · n8n v1.71 · <80ms
What type of business are you running? I'll show you exactly which processes we'd automate first and your estimated ROI.
Powered by n8n + Claude Opus 4.7 Get my free automation plan →
n8n Code Node: 15 JavaScript Examples You Can Copy and Paste
Guides 11 min read · 2,362 words

n8n Code Node: 15 JavaScript Examples You Can Copy and Paste

Fifteen n8n Code node snippets that work as pasted: the return format n8n expects, looping over items, filtering, splitting arrays, reading earlier nodes, dates with Luxon and more.

Steve, founder of PURIST

November 6, 2026

PURIST: Stuck on n8n? Our n8n experts fix and build workflows like this one, at a fixed price →

The Code node is where n8n stops being a drag-and-drop tool and becomes a programming environment. It is also where most people get stuck, because n8n expects data in one specific shape and the error messages do not always say why a snippet fails. This page collects fifteen JavaScript examples that run as pasted, grouped by the job they do, with the rule that makes each one work.

In short. Every Code node must return an array of objects, each with a json key that holds an object: [{ json: {...} }]. In the default mode ("Run Once for All Items") you read every input with $input.all(). In "Run Once for Each Item" you read the current one with $json. Almost every Code node error comes from breaking one of these two rules.

n8n Code Node: 15 JavaScript Examples You Can Copy and Paste: workflow diagram
The Code node receives items, transforms them, and must hand back items in the same shape. Illustration: PURIST.

The one rule: what a Code node must return

n8n passes data between nodes as an array of items. Each item is an object with a json key, and json must itself be an object, not an array or a string. The official documentation lists three errors that all come from this rule: "Code doesn't return items properly", "A 'json' property isn't an object" and "Code doesn't return an object".

javascript
// Valid output: an array of items, each item has a json object
return [
  { json: { name: 'Ana', city: 'Lyon' } },
  { json: { name: 'Leo', city: 'Paris' } },
];

If you return the input items unchanged, you already have the right shape, because $input.all() gives you items in that format.

Choose the right mode first

The Code node has two modes, and the variables you can use depend on the mode.

ModeWhen the code runsHow you read data
Run Once for All Items (default)Once, whatever the number of items$input.all(), $input.first(), $input.last()
Run Once for Each ItemOnce per input item$json or $input.item.json

Use "All Items" when you need to compare items, count, group, dedupe or sort. Use "Each Item" when every item is transformed on its own, which keeps the code shorter.

n8n Code Node: 15 JavaScript Examples You Can Copy and Paste: node settings
The three settings behind most Code node failures: mode, return format and Always Output Data. Illustration: PURIST.

Examples: transform every item

1. Add a field to every item

javascript
// Mode: Run Once for All Items
for (const item of $input.all()) {
  item.json.fullName = `${item.json.firstName} ${item.json.lastName}`;
}
return $input.all();

2. The same thing in "Run Once for Each Item"

javascript
// Mode: Run Once for Each Item
$json.fullName = `${$json.firstName} ${$json.lastName}`;
return $input.item;

3. Keep only some fields

javascript
return $input.all().map((item) => ({
  json: { email: item.json.email, company: item.json.company },
}));

4. Clean and normalise text

javascript
return $input.all().map((item) => ({
  json: {
    ...item.json,
    email: String(item.json.email || '').trim().toLowerCase(),
    phone: String(item.json.phone || '').replace(/[^0-9+]/g, ''),
  },
}));

Examples: filter, dedupe and sort

5. Filter items

javascript
return $input.all().filter((item) => item.json.status === 'paid');

Returning an empty array is allowed. The workflow simply has no items after this node. If later nodes must still run, turn on "Always Output Data" in the node settings.

6. Remove duplicates by email

javascript
const seen = new Set();
return $input.all().filter((item) => {
  const key = String(item.json.email || '').toLowerCase();
  if (!key || seen.has(key)) return false;
  seen.add(key);
  return true;
});

For duplicates across executions (the same lead arriving twice on different days), use the Remove Duplicates node instead. The n8n documentation recommends it because it can remember values between runs.

7. Sort by a date field

javascript
return $input.all().sort(
  (a, b) => new Date(b.json.createdAt) - new Date(a.json.createdAt)
);

Examples: reshape arrays

8. Split one item holding an array into many items

An API often returns one item such as { orders: [...] }. Most nodes expect one item per order.

javascript
const out = [];
for (const item of $input.all()) {
  for (const order of item.json.orders || []) {
    out.push({ json: order });
  }
}
return out;

The Split Out node does the same thing without code. Use code when you also need to transform each element.

9. Combine many items into one

javascript
return [{
  json: {
    count: $input.all().length,
    emails: $input.all().map((i) => i.json.email),
  },
}];

10. Group and total

javascript
const totals = {};
for (const { json } of $input.all()) {
  totals[json.customer] = (totals[json.customer] || 0) + Number(json.amount || 0);
}
return Object.entries(totals).map(([customer, total]) => ({ json: { customer, total } }));

Examples: read other nodes and the workflow

11. Read the output of an earlier node by name

javascript
const contacts = $('Get contacts').all();
const firstDeal = $('Get deals').first().json;
return contacts.map((c) => ({ json: { ...c.json, dealName: firstDeal.name } }));

$('Node name').all(), .first(), .last() and .item all work in the Code node. The name must match the node title exactly, including spaces.

12. Check that a node ran before reading it

When a workflow has branches, the node you reference may not have run in this execution. Reading it then fails with "Referenced node is unexecuted". The documented guard is isExecuted:

javascript
const crm = $('Create in CRM').isExecuted ? $('Create in CRM').first().json : null;
return [{ json: { createdInCrm: Boolean(crm) } }];

13. Add execution details for logging

javascript
return $input.all().map((item) => ({
  json: {
    ...item.json,
    workflow: $workflow.name,
    executionId: $execution.id,
    mode: $execution.mode, // "test" or "production"
  },
}));

Examples: dates and errors

14. Work with dates using Luxon

n8n ships the Luxon library and exposes DateTime and $now in the Code node.

javascript
return $input.all().map((item) => {
  const created = DateTime.fromISO(item.json.createdAt);
  return {
    json: {
      ...item.json,
      ageInDays: Math.floor($now.diff(created, 'days').days),
      followUpOn: created.plus({ days: 3 }).toFormat('yyyy-LL-dd'),
    },
  };
});

15. Stop the workflow with a clear error

javascript
for (const item of $input.all()) {
  if (!item.json.email) {
    throw new Error(`Missing email on record ${item.json.id}`);
  }
}
return $input.all();

A thrown error stops the execution and, if you set one, starts your error workflow. The message you write is what you will read in the alert, so make it specific.

Debugging a Code node

  • Use console.log() and open your browser developer console while you test. The documentation confirms the Code node writes there.
  • Test with the real data. Pin the output of the previous node so you can rerun the Code node without calling the API again.
  • If the node returns nothing, check the mode. $json only exists in "Run Once for Each Item".
  • Test the expression parts first with our free n8n Expression Tester, and find the exact path of a nested field with the JSON Path Finder.

When not to use the Code node

The Code node is not the best tool for everything. The n8n documentation itself points to better options for some jobs:

  • HTTP calls: use the HTTP Request node. It handles credentials, retries, pagination and batching for you.
  • Credentials: Code nodes cannot read stored credentials by design (see our guide to environment variables and credentials in the Code node).
  • Simple field mapping: the Edit Fields (Set) node is easier for the next person to read.
  • Duplicates across runs: the Remove Duplicates node.

Worked example: clean a lead list before it reaches your CRM

Here is a complete, realistic job that combines several snippets above. A form tool sends leads through an HTTP Request node. Some emails have capitals and spaces, some leads are duplicates, and the CRM rejects records without a company. The Code node fixes all three in one pass, so the CRM node receives only clean, unique, complete records.

  1. 1 Add a Code node after the node that fetches leads, mode Run Once for All Items.
  2. 2 Paste the code below.
  3. 3 Pin the input data, run the node, and compare the input and output counts in the panel.
  4. 4 Connect the CRM node and map email, company and source from the output.
javascript
const seen = new Set();
const out = [];
const rejected = [];
for (const item of $input.all()) {
  const d = item.json;
  const email = String(d.email ?? '').trim().toLowerCase();
  const company = String(d.company ?? '').trim();
  if (!email.includes('@')) { rejected.push({ id: d.id, reason: 'invalid email' }); continue; }
  if (!company) { rejected.push({ id: d.id, reason: 'missing company' }); continue; }
  if (seen.has(email)) continue;
  seen.add(email);
  out.push({ json: { email, company, source: d.source ?? 'form', receivedAt: $now.toISO() } });
}
console.log(`kept ${out.length}, rejected ${rejected.length}`);
return out;

Why this version holds up in production:

  • ?? '' turns missing fields into empty strings, so .trim() never crashes on undefined.
  • Rejected records are counted and logged instead of silently dropped. If the count jumps one day, you know the form changed.
  • The timestamp comes from $now, the Luxon date n8n provides, so it follows the instance timezone.

If you need the rejected records downstream (for example to email them to someone), return them as well with a flag such as json.valid = false, then split the flow with an IF node. A Code node has one output, so routing is done by the next node.

Performance: when a Code node gets slow

The Code node handles thousands of items comfortably. Slowness usually comes from one of three patterns:

PatternWhy it is slowFaster version
array.find() inside a loopScans the whole array for every itemBuild a Map once, then map.get(key)
Per-item mode on large listsThe code starts once per item"Run Once for All Items" with one loop
Rebuilding big objects with spread in a loopCopies all fields on every passMutate item.json directly, then return the items

For very large volumes, process in batches with a Loop Over Items node and keep each Code node run small.

Troubleshooting table

SymptomLikely causeFix
"Code doesn't return items properly"Returned values, not { json } itemsreturn list.map((v) => ({ json: { v } }))
$json is not definedDefault mode is All ItemsUse $input.all(), or switch mode
items is not definedSnippet copied from the old Function nodeReplace items with $input.all()
Next nodes do not runThe code returned []Turn on Always Output Data, or handle the empty case
"Referenced node is unexecuted"$('Node') points to a node that did not runGuard with .isExecuted, or rewire
Dates are off by hoursMixed timezonesUse DateTime with an explicit zone, and check the workflow timezone setting

Common mistakes to avoid

  • Doing in code what a node already does. Filter, Sort, Remove Duplicates, Split Out, Aggregate and Edit Fields cover many jobs, and the next person can read them without JavaScript.
  • Hiding business rules in code. If a rule changes often (a price threshold, a list of regions), put it in an Edit Fields node or a custom variable and read it, so nobody has to edit code to change it.
  • Swallowing errors. A try { } catch { } with an empty catch turns a broken API into silent missing data. Throw a clear error, or return the problem as data.
  • Huge Code nodes. Several small, named Code nodes are easier to debug than one 300-line node.

Production checklist

  • The mode chosen on purpose (All Items or Each Item).
  • Every return path returns [{ json: {...} }], including empty cases.
  • Optional fields read with ?. and ??, so one incomplete record does not stop the run.
  • Errors thrown with a specific message that names the record.
  • A sticky note above the node explaining what it does, for the next person.

Frequently asked questions

What is the difference between $json and $input.all() in the n8n Code node?

$json is the current item and only exists in "Run Once for Each Item" mode. $input.all() returns every input item and is what you use in the default "Run Once for All Items" mode.

Can I use import in the n8n Code node?

No. The documentation says import and export are not supported by the sandbox. Use require() instead, and on self-hosted n8n allow the module with NODE_FUNCTION_ALLOW_BUILTIN or NODE_FUNCTION_ALLOW_EXTERNAL. See how to fix "Cannot find module".

Can the Code node return an empty result?

Yes. Returning [] is valid. The next nodes will not run unless you enable "Always Output Data" in the node settings.

Is the Code node slower than built-in nodes?

For normal data volumes the difference does not matter. Python is slower than JavaScript in the Code node, according to the n8n documentation, so prefer JavaScript for large item counts.

How do I loop over items in the n8n Code node?

In "Run Once for All Items" mode, use for (const item of $input.all()) { ... } and return the modified items. In "Run Once for Each Item" mode, n8n does the loop for you and $json is the current item.

Can the Code node make HTTP requests?

The HTTP Request node is the documented way to call APIs: it handles credentials, retries and pagination. Keep the Code node for preparing the data and reading the response.

How do I use dates in the n8n Code node?

n8n includes Luxon. Use DateTime.fromISO() to parse, $now for the current time, .plus() and .diff() for calculations, and .toFormat() to format.

How do I debug a Code node?

Pin the input data, add console.log() lines, open the browser developer console, and run only that node. Check the output panel for the item count and shape.

Tags

n8ncode nodejavascriptn8n examplesworkflow automation
Steve, founder of PURIST

Steve founded PURIST, a workflow automation studio working with n8n, Make and Claude AI, and is the point of contact on every project. Prices and features in our articles come from vendor documentation and public pricing pages. How we research and score tools.

Complete guide

Automation Tools & Platforms

8 min read n8n Code Node With Multiple Inputs: 3 Methods That Work 7 min read Fix "Cannot find module" in the n8n Code Node (npm Pack… 7 min read n8n Code Node Errors Fixed: "Code doesn't return items … 7 min read $env and Credentials in the n8n Code Node: What Works a… 7 min read n8n Code Node Binary Data: Read, Change and Return File… 7 min read Python in the n8n Code Node (n8n 2.x): Setup, Syntax an… 7 min read Fix n8n "The requested webhook is not registered" (Test… 6 min read n8n Webhook URL: Test vs Production, and How to Change … 7 min read n8n Respond to Webhook: Return JSON, Status Codes, Redi… 8 min read Secure an n8n Webhook: Header Auth, Basic Auth, JWT and… 7 min read n8n Webhook Not Working? 10 Causes and How to Fix Each … 7 min read n8n HTTP Request Pagination: Every Pattern With Working… 7 min read n8n HTTP Request Authentication: API Keys, Bearer Token… 7 min read n8n HTTP Request Timeout and "Aborted" Errors: Causes a… 7 min read Upload and Download Files With the n8n HTTP Request Nod… 6 min read Fix ECONNREFUSED in n8n: Docker, localhost and 127.0.0.… 6 min read n8n 429 Too Many Requests: Batching, Retries and Rate L… 6 min read Fix redirect_uri_mismatch for n8n OAuth2 Credentials (G… 7 min read n8n Expression Errors Fixed: "Referenced node is unexec… 6 min read Anatomy Claude skill: what it is, how to install it, an… 5 min read How to explain a business process with the Anatomy skil… 5 min read Anatomy vs Mermaid vs Excalidraw: which to explain a wo… 14 min read n8n LinkedIn Job Automation: Auto-Apply, Track, and Fol… 16 min read n8n HTTP Request Node: Complete Documentation and Examp… 18 min read The future of automation: how our engineering team is s… 8 min read n8n vs Make vs Zapier: the honest comparison your busin… 11 min read n8n vs Make vs Zapier: an honest comparison for product… 7 min read Webhook vs polling: the architecture decision that dete… 24 min read n8n tutorial: build your first production workflow in u… 26 min read The 9 best Zapier alternatives in 2026: an honest ranki… 21 min read Make.com tutorial: build powerful automations without c… 19 min read Automation consultant vs DIY: how to decide what is rig… 14 min read n8n Self-Hosted vs Cloud: The Complete Decision Guide (… 15 min read 5 Zapier Free Alternatives That Handle Real Production … 15 min read WhatsApp Business Automation With n8n: Build a 24/7 Cus… 17 min read Google Workspace Automation: 15 Workflows for Sheets, D… 16 min read Claude AI for Business Automation: What It Does, What I… 15 min read Airtable Automation With n8n: 10 Workflows That Make Yo… 15 min read Droven.io AI Automation Tools: Full Review and Best Alt… 14 min read Droven.io RPA and Business Automation: An Honest 2026 R… 15 min read Enterprise Workflow Automation: The Complete Guide for … 13 min read Document Workflow Automation: Software, Implementation,… 14 min read Marketing Automation Workflow: From Content Creation to… 16 min read Ad Campaign Workflow Data Model and SDR Inbound Pipelin… 14 min read ComfyUI Workflows for Business: Product Photography, Ma… 13 min read GPT-5.2 for Business Workflows and the spec-workflow-mc… 17 min read ServiceNow vs IBM BAW vs n8n: Enterprise Workflow Autom… 16 min read 9 Best Workflow Automation Tools for Small Business in …

Keep reading

More from the blog.

All articles

From audit to deployment

Experience the automation
these articles are about.

Get my free automation plan →