Tips > Building Workflows

Replace Node Chains With a Single Code Node for Complex Logic

When you find yourself building a chain of IF > Switch > Set > IF > Merge nodes to implement branching business logic, stop and consider whether a single Cod...

When you find yourself building a chain of IF > Switch > Set > IF > Merge nodes to implement branching business logic, stop and consider whether a single Code node would be clearer. The threshold is roughly three or more conditional branches that feed into the same downstream node.

Real-world example: An order processing workflow must classify orders into tiers (standard, priority, VIP), apply different discount rules, flag fraud risks, and set shipping methods -- all before passing to the fulfillment API.

// Mode: Run Once for Each Item
const order = $input.item.json;
const total = order.lineItems.reduce((sum, li) => sum + li.price * li.qty, 0);

// Tier classification
let tier = 'standard';
if (order.customerLifetimeValue > 10000 || order.tags?.includes('vip')) {
  tier = 'vip';
} else if (total > 500 || order.isPriorityMember) {
  tier = 'priority';
}

// Discount rules per tier
const discountMap = { standard: 0, priority: 0.05, vip: 0.10 };
const discount = total * discountMap[tier];

// Fraud flag heuristics
const fraudRisk = (
  total > 2000 &&
  order.isNewCustomer &&
  order.shippingCountry !== order.billingCountry
);

// Shipping method
const shipping = tier === 'vip' ? 'overnight' :
                 tier === 'priority' ? '2day' : 'ground';

return [{
  json: {
    ...order,
    tier,
    subtotal: total,
    discount,
    finalTotal: total - discount,
    fraudRisk,
    shippingMethod: shipping,
  }
}];
```text
One readable Code node replaces what would be 8-12 nodes on the canvas, making the logic auditable and version-controllable.

**Related:** [Use Edit Fields in "Map Each" Mode for Simple Renames](../data-transformation/01-use-edit-fields-in-map-each-mode-for-simple-renames.md) | [Configure Payload Size and Binary Data Mode for Large Files](../performance-and-large-files/01-configure-payload-size-and-binary-data-mode-for-large-files.md)

Showcase builds

19 complete workflows from my own projects, each with its n8n workflow JSON to import. Showcase entries link the file at the end of the article.

See the showcase builds

Keep reading

191 entries grouped by topic, from first workflow to queue mode. Free, no signup.

Browse the encyclopedia

Need it built?

I design, build and run n8n systems for clients. Every engagement starts with a $1,500 diagnostic audit, credited toward the build.

Book a 20-minute call