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 With Multiple Inputs: 3 Methods That Work
Guides 8 min read · 1,655 words

n8n Code Node With Multiple Inputs: 3 Methods That Work

The Code node only has one input connector. Three reliable ways to work with two or more data sources anyway, with code you can paste and the trap that breaks each one.

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 →

Search "n8n code node 2 inputs" and you will find the same question asked many times: the Code node has a single input connector, so how do you combine customers from one branch with orders from another? The answer is that you do not need a second connector. n8n gives you two clean ways to bring several data sources into one Code node, plus a third pattern for loops.

In short. Either merge the branches first with a Merge node and connect the result to the Code node, or keep one input and read the other node directly with $('Node name').all(). The second method is the quickest, but the referenced node must have run in the same execution.

n8n Code Node With Multiple Inputs: 3 Methods That Work: workflow diagram
Two ways to bring two data sources into one Code node: merge the branches first, or read the second node by name. Illustration: PURIST.

Why the Code node has only one input

Most n8n nodes take one input and process its items. The Merge node exists precisely to join branches. Keeping the Code node single-input keeps item linking predictable: n8n knows which input item produced which output item. So instead of looking for a hidden second input, use one of the methods below.

Method 1: Merge first, then code

Use this when both sources should become one combined list before your logic runs.

  1. 1 Connect branch A to input 1 of a Merge node and branch B to input 2.
  2. 2 Choose the merge mode. "Append" puts all items one after the other. "Combine" with "Matching Fields" joins items that share a key such as email or id.
  3. 3 Connect the Merge node to the Code node.

If you chose "Append", the Code node receives both lists in one array. Tag the items upstream (for example with an Edit Fields node that sets source: 'crm') so the code can tell them apart:

javascript
const all = $input.all();
const crm = all.filter((i) => i.json.source === 'crm');
const billing = all.filter((i) => i.json.source === 'billing');
return [{ json: { crmCount: crm.length, billingCount: billing.length } }];

When the join itself is the whole job, "Combine" by matching fields often removes the need for code entirely.

n8n Code Node With Multiple Inputs: 3 Methods That Work: node settings
Reading a lookup node by name, with an isExecuted guard and a Map index. Illustration: PURIST.

Method 2: One input, read the other node by name

Use this when one source is "the items to process" and the other is a lookup table. Connect only the main branch to the Code node, and make sure the other node runs earlier in the same path.

javascript
// Main input: orders. Lookup: the node called "Get customers".
const customers = $('Get customers').all().map((i) => i.json);
const byId = new Map(customers.map((c) => [String(c.id), c]));
return $input.all().map((order) => {
  const customer = byId.get(String(order.json.customerId)) || {};
  return {
    json: {
      ...order.json,
      customerName: customer.name || null,
      customerEmail: customer.email || null,
    },
  };
});

Building a Map first matters. Searching an array for every order works on ten records and becomes slow on ten thousand.

The trap: "Referenced node is unexecuted"

$('Node name') only returns data if that node has run in the current execution. If it sits on a branch that did not run, or after the Code node, n8n raises "Referenced node is unexecuted" (also shown as "Can't get data for expression"). Two fixes:

  • Put the lookup node before the Code node on the same path, so it always runs first.
  • Guard the read with the documented isExecuted property:
javascript
const customers = $('Get customers').isExecuted
  ? $('Get customers').all().map((i) => i.json)
  : [];

Method 3: Data from a loop

Inside a "Loop Over Items" pattern, the Code node may run several times. $('Node name').all() accepts two optional arguments, branchIndex and runIndex, documented as $('Node').all(branchIndex?, runIndex?). Use $runIndex to read the matching run:

javascript
const pageItems = $('Fetch page').all(0, $runIndex);
return pageItems;

If you only need everything once the loop is done, put the Code node after the loop's "done" output instead. It is simpler and avoids run-index bugs.

Which method to choose

SituationBest method
Two lists to join on a shared keyMerge node in "Combine" mode, often no code needed
Two lists to analyse togetherMerge in "Append", then Code
Items plus a lookup tableOne input, read the table with $('Node').all()
Data produced inside a loopCode after the loop, or all(0, $runIndex)

Worked example: invoices joined with customer records

A finance team exports unpaid invoices from their billing tool and wants a reminder email per customer, with the customer's account manager in copy. Invoices and customers live in two systems.

  1. 1 Get unpaid invoices (HTTP Request to the billing API): one item per invoice, with customerId, amount and dueDate.
  2. 2 Get customers (CRM node), placed on the same path before the Code node: one item per customer, with id, email and ownerEmail.
  3. 3 Build reminders (Code node, All Items), connected to Get unpaid invoices only.
javascript
const customers = $('Get customers').all().map((i) => i.json);
const byId = new Map(customers.map((c) => [String(c.id), c]));
const grouped = new Map();
for (const { json: inv } of $input.all()) {
  const c = byId.get(String(inv.customerId));
  if (!c) continue;
  if (!grouped.has(c.id)) grouped.set(c.id, { email: c.email, cc: c.ownerEmail, invoices: [], total: 0 });
  const g = grouped.get(c.id);
  g.invoices.push({ number: inv.number, amount: inv.amount, dueDate: inv.dueDate });
  g.total += Number(inv.amount || 0);
}
return [...grouped.values()].map((g) => ({ json: g }));
  1. 1 Send reminder (Gmail or SMTP node): one email per customer, listing their invoices.

The output has one item per customer, not per invoice, which is exactly what the email node needs. Note how the lookup node is placed before the Code node in the same path: that guarantees it has run when the code reads it.

Merge node modes in one table

Since the Merge node is often the cleaner option, here is what each mode does before data reaches your Code node:

Merge modeResultTypical use
AppendAll items from input 1, then all from input 2Analyse two lists together
Combine by matching fieldsItems joined where a key matchesOrders + customers on customerId
Combine by positionItem 1 with item 1, item 2 with item 2Two lists produced in the same order
Combine all possible combinationsEvery pairRare; grows fast
Choose branchWaits for both, outputs oneSynchronise two branches

If "Combine by matching fields" already produces what you need, you may not need a Code node at all.

Troubleshooting table

SymptomLikely causeFix
"Referenced node is unexecuted"Lookup node on another branch or after the Code nodeMove it before, same path, or guard with .isExecuted
Lookup returns an empty arrayThe lookup node returned no items in this runCheck its output; handle the empty case
Every order gets the same customerUsing .first() instead of a keyed lookupBuild a Map keyed on the ID
Matches fail on some IDs12 (number) vs "12" (string)Normalise with String() on both sides
Merge outputs nothingOne input received no itemsCheck both branches ran; consider "Always Output Data" upstream

Common mistakes to avoid

  • Renaming the lookup node. $('Get customers') breaks silently if someone renames the node to "Get CRM customers". Mention the dependency in the node's notes.
  • Joining on display names. Names change and collide. Join on stable IDs or normalised emails.
  • Fetching the lookup inside a loop. Calling the CRM once per order multiplies API calls and hits rate limits. Fetch the lookup once, index it, then loop.

Production checklist

  • Lookup nodes placed before the Code node on the same path.
  • isExecuted guards on any node that sits on an optional branch.
  • A Map index for lookups on more than a few hundred records.
  • Node names referenced in code not renamed later (or the code updated with them).

Frequently asked questions

Can I add a second input to the n8n Code node?

No. The Code node has one input connector. Use a Merge node before it, or read other nodes by name with $('Node name').all().

Why does $('Node name') return nothing or an error?

The referenced node did not run in this execution, or its name is misspelled. Node names are matched exactly. Check the node title and make sure it runs before the Code node.

Which merge mode should I use before a Code node?

"Append" if your code needs both full lists. "Combine" with matching fields if you only need records joined on a key, in which case you may not need code at all.

Is $node["Name"] still supported?

Older workflows use $node["Name"].json. Current documentation uses $('Node name'), which also supports .all(), .first(), .last() and .item. Prefer it in new workflows.

What is the difference between Merge and $('Node').all() in n8n?

Merge combines two branches into one input, visibly, on the canvas. $('Node').all() reads another node's output from code without a connection. Merge is clearer for joins; references are faster for lookup tables.

Does the referenced node need to be connected to the Code node?

No, but it must have run earlier in the same execution, usually by sitting before the Code node on the same path.

Can I read a node that ran inside a loop?

Yes. $('Node').all(branchIndex, runIndex) reads a specific run; $runIndex gives the current one.

Tags

n8ncode nodemerge nodemultiple inputsjavascript
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

11 min read n8n Code Node: 15 JavaScript Examples You Can Copy and … 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 →