n8nen.nl logo n8nen.nl

N8N IF & Switch Nodes: Conditional Logic voor Slimme Workflows [Complete Gids]

2025-08-29 Sam Hutting
N8N IF & Switch Nodes: Conditional Logic voor Slimme Workflows [Complete Gids]
N8N Conditional Logic: IF & Switch Nodes Intelligente Beslissingen in Je Workflows IF Node Binary Decision Making IN condition TRUE FALSE Switch Node Multi-Path Routing IN switch(value) Route 1 Route 2 Route 3 Route 4 Default Decision Tree Complex Logic Flows Comparison Operations • == Equal • != Not Equal • > Greater Than • < Less Than • contains() • startsWith() • endsWith() • isEmpty() • regex match • AND Logic • OR Logic • Date/Time • Boolean • Number • String • Object • Array • Expressions Common Use Cases 📊 Data Validation & Filtering 🔄 Order Status Processing 📧 Email Routing by Domain 💰 Price Tier Classification 🏷️ Customer Segmentation ⚠️ Error Handling & Recovery 🔐 Permission Based Access 🎯 A/B Testing Workflows Best Practices ✓ Use IF for binary decisions ✓ Switch for 3+ routes ✓ Validate data early ✓ Handle edge cases ✓ Use expressions wisely ✓ Test all branches ✓ Document complex logic ✓ Optimize performance

Intelligente Workflows met Conditional Logic

In de wereld van workflow automation is het vermogen om intelligente beslissingen te nemen het verschil tussen simpele automatisering en echte business intelligence. N8N's IF en Switch nodes vormen het hart van conditional logic, waarmee je workflows kunnen reageren, aanpassen en routeren op basis van real-time data en business rules.

Of je nu orders wilt filteren op status, klanten wilt segmenteren op gedrag, of complexe approval flows wilt bouwen - conditional logic maakt het mogelijk. Deze comprehensive gids duikt diep in de werking van IF en Switch nodes, van basis binary decisions tot geavanceerde multi-path routing en decision trees.

💡 Pro Tip: IF vs Switch

Gebruik de IF node voor simpele true/false beslissingen (binary logic). Kies de Switch node wanneer je 3 of meer verschillende routes nodig hebt. Dit maakt je workflows leesbaarder en efficiënter.

IF Node: Binary Decision Making

Wat is de IF Node?

De IF node is N8N's fundamentele building block voor conditional branching. Het evalueert een of meerdere condities en splitst de workflow in twee paden: TRUE (wanneer de conditie klopt) en FALSE (wanneer de conditie niet klopt).

IF Node Configuratie

Parameter Beschrijving Voorbeeld
Conditions De condities die geëvalueerd worden {{$json.status}} == "active"
Combine AND of OR voor multiple conditions AND (alle condities moeten waar zijn)
Data Type Type data voor vergelijking String, Number, Boolean, Date

Praktisch Voorbeeld: Order Validation

// IF Node: Check of order geldig is
{
  "conditions": {
    "string": [
      {
        "value1": "={{$json.order_status}}",
        "operation": "equals",
        "value2": "pending"
      }
    ],
    "number": [
      {
        "value1": "={{$json.order_total}}",
        "operation": "larger",
        "value2": 100
      }
    ],
    "boolean": [
      {
        "value1": "={{$json.customer.verified}}",
        "operation": "true"
      }
    ]
  },
  "combineOperation": "and"  // Alle condities moeten waar zijn
}

// Output:
// TRUE → Process order
// FALSE → Send to manual review

Switch Node: Multi-Path Routing

Waarom Switch Node?

Waar de IF node beperkt is tot twee outputs, biedt de Switch node onbeperkte routing mogelijkheden. Perfect voor scenarios zoals:

  • Order routing op basis van prioriteit (low, medium, high, urgent)
  • Customer segmentation (bronze, silver, gold, platinum)
  • Department routing voor support tickets
  • Multi-language content delivery
  • Regional processing rules

Switch Node Modes

🔄 Rules Mode vs Expression Mode

  • Rules Mode: Visueel rules bouwen voor elke output
  • Expression Mode: JavaScript expression voor output index

Complex Switch Example: Customer Support Routing

// Switch Node Configuration: Support Ticket Routing
{
  "mode": "rules",
  "dataType": "string",
  "value1": "={{$json.ticket}}",
  "rules": {
    "rules": [
      {
        // Output 0: Technical Issues
        "operation": "contains",
        "value2": "technical",
        "output": 0
      },
      {
        // Output 1: Billing Questions
        "operation": "contains", 
        "value2": "billing",
        "output": 1
      },
      {
        // Output 2: Sales Inquiries
        "operation": "contains",
        "value2": "pricing",
        "output": 2
      },
      {
        // Output 3: Priority Support
        "conditions": {
          "string": [
            {
              "value1": "={{$json.customer_tier}}",
              "operation": "equals",
              "value2": "enterprise"
            }
          ]
        },
        "output": 3
      }
    ],
    "fallbackOutput": 4  // Default: General Support
  }
}

Expression Mode voor Dynamic Routing

// Switch Node: Expression Mode
// Route based on calculated priority score

const priorityScore = $json.urgency * $json.impact;
const customerTier = $json.customer.tier;

// Dynamic routing logic
if (priorityScore >= 16 && customerTier === 'enterprise') {
  return 0; // Critical - Immediate attention
} else if (priorityScore >= 12) {
  return 1; // High priority
} else if (priorityScore >= 8) {
  return 2; // Medium priority
} else if (priorityScore >= 4) {
  return 3; // Low priority
} else {
  return 4; // Backlog
}

Comparison Operations Deep Dive

String Operations

Operation Beschrijving Voorbeeld
equals Exacte match status == "active"
contains Bevat substring email.contains("@gmail")
startsWith Begint met url.startsWith("https")
endsWith Eindigt met file.endsWith(".pdf")
regex Regular expression /^[A-Z]{2}\d{4}$/

Number Operations

// Number comparison examples
{
  "larger": price > 100,
  "largerEqual": quantity >= 10,
  "smaller": discount < 50,
  "smallerEqual": stock <= 5,
  "equal": count === 0,
  "notEqual": remainder !== 0,
  "between": age >= 18 && age <= 65,
  "modulo": orderNumber % 2 === 0  // Even/odd check
}

Date & Time Operations

// Date comparison in IF/Switch nodes
{
  "conditions": {
    "dateTime": [
      {
        "value1": "={{$json.created_at}}",
        "operation": "after",
        "value2": "={{$today.minus(7, 'days')}}"
      }
    ]
  }
}

// Common date operations:
// - after: Date is after specified date
// - before: Date is before specified date
// - between: Date falls between two dates
// - isWeekend: Check if date is Saturday/Sunday
// - isWorkday: Check if date is Monday-Friday

Geavanceerde Conditional Patterns

Pattern 1: Cascading IF Nodes

🔀 Waterfall Decision Logic

Voor complexe beslissingslogica kun je meerdere IF nodes in serie schakelen:

  1. IF Node 1: Check authentication
  2. IF Node 2: Verify permissions
  3. IF Node 3: Validate data
  4. IF Node 4: Check rate limits
  5. Process: Execute main logic
// Cascading validation pattern
workflow = {
  nodes: [
    {
      name: "Check Auth",
      type: "IF",
      condition: "$json.headers.authorization !== null",
      true: "Check Permissions",
      false: "Return 401"
    },
    {
      name: "Check Permissions",
      type: "IF",
      condition: "$json.user.roles.includes('admin')",
      true: "Validate Data",
      false: "Return 403"
    },
    {
      name: "Validate Data",
      type: "IF",
      condition: "$json.data.isValid()",
      true: "Process Request",
      false: "Return 400"
    }
  ]
};

Pattern 2: Parallel Processing with Switch

// Switch node voor parallel department processing
{
  "name": "Department Router",
  "type": "Switch",
  "mode": "expression",
  "expression": `
    // Determine department based on product category
    const category = $json.product.category;
    const departments = {
      'electronics': 0,
      'clothing': 1,
      'food': 2,
      'books': 3,
      'sports': 4
    };
    
    return departments[category] || 5; // Default to general
  `,
  "outputs": [
    "Electronics Team",
    "Fashion Team",
    "Food Safety Team",
    "Publishing Team",
    "Sports Team",
    "General Processing"
  ]
}

Pattern 3: Decision Trees

⚠️ Complexity Warning

Bij zeer complexe decision trees (>10 beslispunten), overweeg een Code node met een decision table of integratie met een dedicated rule engine voor betere maintainability.

// Complex decision tree voor loan approval
const loanDecisionTree = {
  // Level 1: Credit Score Check
  creditScore: {
    condition: "score >= 700",
    true: {
      // Level 2: Income Verification
      income: {
        condition: "annual_income >= 50000",
        true: {
          // Level 3: Debt-to-Income Ratio
          dti: {
            condition: "debt_ratio <= 0.4",
            true: "AUTO_APPROVE",
            false: "MANUAL_REVIEW"
          }
        },
        false: {
          // Level 3: Collateral Check
          collateral: {
            condition: "has_collateral === true",
            true: "CONDITIONAL_APPROVE",
            false: "DECLINE"
          }
        }
      }
    },
    false: {
      // Level 2: Special Programs
      firstTimeBuyer: {
        condition: "is_first_time === true",
        true: "SPECIAL_PROGRAM",
        false: "DECLINE"
      }
    }
  }
};

Real-World Use Cases

Use Case 1: E-commerce Order Processing

🛒 Order Fulfillment Workflow

Intelligente order routing op basis van multiple factoren:

// Complete order processing logic
const orderWorkflow = {
  // Step 1: Validate Order
  validateOrder: {
    type: "IF",
    conditions: [
      "order.items.length > 0",
      "order.payment.verified === true",
      "order.shipping.address !== null"
    ],
    combine: "AND"
  },
  
  // Step 2: Check Inventory
  checkInventory: {
    type: "IF",
    condition: "allItemsInStock(order.items)",
    true: "routeByPriority",
    false: "backorderProcess"
  },
  
  // Step 3: Route by Priority
  routeByPriority: {
    type: "Switch",
    expression: `
      if (order.shipping.type === 'express') return 0;
      if (order.total > 500) return 1;
      if (order.customer.tier === 'vip') return 2;
      return 3; // Standard processing
    `,
    outputs: [
      "Express Fulfillment",
      "Priority Processing",
      "VIP Handling",
      "Standard Queue"
    ]
  }
};

Use Case 2: Customer Support Automation

Ticket Type Conditions Routing
Critical Keywords: "down", "broken", "urgent" Immediate escalation
Technical Category = "technical" OR contains API Tech support team
Billing Contains "invoice", "payment", "refund" Finance department
Sales New customer AND contains "pricing" Sales team

Use Case 3: Data Quality Control

// Data validation met multiple IF nodes
const dataQualityChecks = [
  {
    name: "Check Completeness",
    type: "IF",
    condition: `
      $json.requiredFields.every(field => 
        $json.data[field] !== null && 
        $json.data[field] !== ''
      )
    `
  },
  {
    name: "Validate Email",
    type: "IF",
    condition: "/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($json.email)"
  },
  {
    name: "Check Phone Format",
    type: "IF",
    condition: "/^\+?[1-9]\d{1,14}$/.test($json.phone)"
  },
  {
    name: "Validate Date Range",
    type: "IF",
    condition: `
      new Date($json.startDate) < new Date($json.endDate) &&
      new Date($json.startDate) > new Date()
    `
  }
];

Performance Optimization

Tips voor Snellere Conditional Logic

⚡ Performance Best Practices

  • Plaats meest waarschijnlijke conditions eerst
  • Gebruik early exit patterns voor snelle rejects
  • Minimaliseer complex expressions in hot paths
  • Cache herbruikbare calculations
  • Gebruik Code node voor zeer complexe logic

Optimization Pattern: Early Exit

// Early exit pattern voor performance
const optimizedValidation = {
  // Quick rejects eerst
  quickChecks: [
    {
      name: "Check Required Fields",
      condition: "data !== null",
      false: "REJECT_IMMEDIATELY"
    },
    {
      name: "Check Authorization",
      condition: "user.isAuthorized",
      false: "REJECT_UNAUTHORIZED"
    }
  ],
  
  // Expensive checks alleen als nodig
  expensiveChecks: [
    {
      name: "Database Lookup",
      condition: "await checkDatabase($json.id)"
    },
    {
      name: "External API Validation",
      condition: "await validateWithAPI($json)"
    }
  ]
};

Error Handling in Conditional Logic

Robust Error Handling Pattern

// Error handling met IF/Switch nodes
const errorHandlingWorkflow = {
  mainProcess: {
    try: "Execute Main Logic",
    catch: "Error Handler"
  },
  
  errorHandler: {
    type: "Switch",
    expression: `
      const errorCode = $json.error?.code || 'UNKNOWN';
      const errorMap = {
        'VALIDATION_ERROR': 0,
        'AUTH_ERROR': 1,
        'RATE_LIMIT': 2,
        'NETWORK_ERROR': 3,
        'DATABASE_ERROR': 4
      };
      return errorMap[errorCode] || 5;
    `,
    outputs: [
      "Handle Validation Error",
      "Handle Auth Error",
      "Handle Rate Limit",
      "Retry with Backoff",
      "Alert Database Team",
      "Generic Error Handler"
    ]
  }
};

Retry Logic met Conditional Nodes

🔄 Smart Retry Pattern

  1. Attempt Operation: Voer actie uit
  2. IF Success: Continue workflow
  3. IF Failure: Check retry count
  4. Switch on Error Type: Bepaal retry strategy
  5. Wait & Retry: Exponential backoff

Integratie met Andere Nodes

Split-Process-Merge Pattern

// Split-Process-Merge met conditional logic
const splitProcessMerge = {
  // 1. Split data met Switch
  split: {
    type: "Switch",
    mode: "expression",
    expression: "$json.category"
  },
  
  // 2. Process each path differently
  processA: {
    nodes: ["Transform A", "Enrich A", "Validate A"]
  },
  processB: {
    nodes: ["Transform B", "API Call B", "Format B"]
  },
  
  // 3. Merge results
  merge: {
    type: "Merge",
    mode: "combine",
    joinMode: "outer",
    outputKey: "processed_items"
  }
};

Conditional Logic met Database Queries

// Database-driven conditional routing
const databaseConditional = {
  // Fetch configuration from database
  getConfig: {
    type: "PostgreSQL",
    query: `
      SELECT routing_rules 
      FROM workflow_config 
      WHERE workflow_id = $1
    `
  },
  
  // Apply dynamic rules
  applyRules: {
    type: "Code",
    code: `
      const rules = $json.routing_rules;
      const data = $input.all();
      
      return data.map(item => {
        for (const rule of rules) {
          if (evaluateRule(item, rule)) {
            return { ...item, route: rule.target };
          }
        }
        return { ...item, route: 'default' };
      });
    `
  },
  
  // Route based on database config
  dynamicRouter: {
    type: "Switch",
    mode: "expression",
    expression: "$json.route"
  }
};

Testing & Debugging Conditional Logic

Test Strategies

🧪 Testing Checklist

  • Test alle mogelijke paths
  • Include edge cases (null, empty, undefined)
  • Test met verschillende data types
  • Valideer error scenarios
  • Check performance met grote datasets
  • Test concurrent execution

Debug Helper Node

// Debug helper voor conditional logic
const debugHelper = {
  name: "Debug Conditional",
  type: "Code",
  code: `
    // Log all conditions and their results
    const conditions = [
      { name: 'Auth Check', result: $json.isAuthenticated },
      { name: 'Permission', result: $json.hasPermission },
      { name: 'Data Valid', result: $json.isValid },
      { name: 'Rate Limit', result: $json.withinLimit }
    ];
    
    console.log('=== Conditional Logic Debug ==');
    conditions.forEach(c => {
      console.log(`${c.name}: ${c.result ? '✅' : '❌'}`);
    });
    
    // Output decision path
    const decisionPath = conditions
      .filter(c => c.result)
      .map(c => c.name)
      .join(' → ');
    
    return {
      conditions,
      decisionPath,
      timestamp: new Date().toISOString()
    };
  `
};

Best Practices & Guidelines

Do's and Don'ts

✅ Do ❌ Don't
Use IF for binary decisions Use IF for 3+ conditions
Validate data early in workflow Nest IF nodes too deeply (>3 levels)
Use Switch for multiple routes Put complex logic in expressions
Handle null/undefined cases Forget default/fallback routes
Document complex logic Ignore error scenarios

Naming Conventions

// Recommended naming patterns
const namingConventions = {
  ifNodes: [
    "Check [Condition]",     // Check Authentication
    "Validate [Data]",       // Validate Email
    "Is [State]",           // Is Premium Customer
    "Has [Property]"        // Has Permission
  ],
  
  switchNodes: [
    "Route by [Criteria]",  // Route by Priority
    "[Entity] Router",      // Order Router
    "Classify [Item]",     // Classify Ticket
    "Distribute [Type]"    // Distribute Task
  ],
  
  branches: [
    "[Condition] Met",     // Validation Met
    "[Condition] Failed",  // Auth Failed
    "[Category] Path",     // Premium Path
    "[Action] Route"      // Process Route
  ]
};

Conclusie: Master Conditional Logic

IF en Switch nodes zijn de ruggengraat van intelligente automation in N8N. Ze transformeren lineaire workflows in dynamische, adaptieve systemen die kunnen reageren op elke situatie. Of je nu simpele filters bouwt of complexe decision trees implementeert, het beheersen van conditional logic is essentieel voor professionele workflow automation.

Key Takeaways

  • ✅ Gebruik IF nodes voor binary decisions (true/false)
  • ✅ Kies Switch nodes voor 3+ routing opties
  • ✅ Implementeer early exit patterns voor performance
  • ✅ Test alle mogelijke paths in je logic
  • ✅ Documenteer complexe beslissingslogica
  • ✅ Handle edge cases en errors gracefully

Next Steps

Nu je conditional logic beheerst, kun je deze kennis combineren met:

🚀 Ready voor Intelligente Workflows?

Ons team van N8N experts helpt je graag met het implementeren van complexe conditional logic en decision trees. Van simpele filters tot enterprise-grade routing systemen.

#n8n #if node #switch node #conditional logic #workflow routing #decision trees #automatisering #business logic