When you move beyond basic automation workflows, you’ll quickly encounter scenarios where different customers, leads, or data points need different treatment. This is where conditional logic becomes your most powerful tool in n8n. Today, we’ll explore how to build sophisticated decision trees that can handle complex business rules automatically.
Understanding Conditional Logic in Business Context
Conditional logic allows your workflows to make smart decisions based on data. Instead of treating every customer the same way, you can create branching paths that deliver personalized experiences at scale.
Real-world examples include:
- Routing high-value leads to senior sales reps while qualifying smaller leads automatically
- Sending different onboarding sequences based on customer plan type and industry
- Escalating support tickets based on customer tier and issue severity
- Processing orders differently based on location, value, and payment method
The IF Node: Your Decision Engine
The IF node is n8n’s primary tool for conditional logic. It evaluates data and routes your workflow down different paths based on whether conditions are true or false.
Basic IF Node Setup
Start with a simple condition:
- Add an IF node to your workflow
- Set your condition type (String, Number, Boolean, etc.)
- Define your comparison (equals, contains, greater than, etc.)
- Set your comparison value
Example: Route leads based on company size
- Condition:
{{$json.company_size}}
Number → Greater Than → 100 - True path: Send to enterprise sales team
- False path: Send to standard sales funnel
Advanced Comparison Options
n8n offers multiple comparison types for different data scenarios:
String Comparisons:
- Contains: Check if text includes specific words
- Starts with/Ends with: Useful for email domains or phone number patterns
- Regex: Pattern matching for complex text validation
Number Comparisons:
- Greater than/Less than: Perfect for revenue, employee count, or age thresholds
- Between: Set ranges for scoring or categorization
Boolean Logic:
- Is empty/Is not empty: Handle missing data gracefully
- Exists/Does not exist: Check for optional fields
Building Multi-Condition Logic
Real business rules often require multiple conditions. Here’s how to handle complex scenarios:
Method 1: Chained IF Nodes
For sequential decision making, chain IF nodes together:
Scenario: Lead scoring and routing
- First IF: Company size > 500 employees?
- True: Continue to next condition
- False: Route to small business team
- Second IF: Budget > $10,000?
- True: Priority lead → Senior sales rep
- False: Standard lead → Junior sales rep
Method 2: Switch Node for Multiple Outcomes
When you have more than two possible outcomes, use the Switch node:
Scenario: Customer support ticket routing
- Case 1: Priority = “High” → Immediate escalation
- Case 2: Priority = “Medium” → Standard queue
- Case 3: Priority = “Low” → Automated response first
- Default: Error handling for unexpected values
Method 3: Code Node for Complex Logic
For sophisticated business rules, use the Code node with JavaScript:
// Complex lead scoring example
const lead = $input.first().json;
let score = 0;
let tier = 'basic';
// Company size scoring
if (lead.company_size > 1000) score += 30;
else if (lead.company_size > 100) score += 20;
else if (lead.company_size > 10) score += 10;
// Budget scoring
if (lead.budget > 50000) score += 25;
else if (lead.budget > 10000) score += 15;
else if (lead.budget > 1000) score += 5;
// Industry multiplier
if (['technology', 'healthcare', 'finance'].includes(lead.industry)) {
score *= 1.2;
}
// Determine tier
if (score >= 50) tier = 'enterprise';
else if (score >= 25) tier = 'professional';
return [{
json: {
...lead,
score: Math.round(score),
tier: tier,
priority: score >= 40 ? 'high' : score >= 20 ? 'medium' : 'low'
}
}];
Advanced Conditional Patterns
Pattern 1: Progressive Qualification
Build workflows that gather information progressively and make decisions at each step:
- Initial qualification: Basic company info
- If qualified: Request budget information
- If budget meets threshold: Schedule demo
- If demo requested: Assign to appropriate sales rep based on deal size
Pattern 2: Fallback Logic
Always plan for unexpected data or failed conditions:
// Robust email validation with fallbacks
const email = $json.email;
let isValid = false;
let domain = 'unknown';
try {
if (email && email.includes('@')) {
domain = email.split('@')[1].toLowerCase();
isValid = true;
// Additional business domain logic
if (['gmail.com', 'yahoo.com', 'hotmail.com'].includes(domain)) {
// Personal email handling
} else {
// Business email handling
}
}
} catch (error) {
// Handle malformed email gracefully
isValid = false;
}
return [{ json: { email, domain, isValid } }];
Pattern 3: Time-Based Conditions
Incorporate timing into your business logic:
Business hours routing:
const now = new Date();
const hour = now.getHours();
const day = now.getDay(); // 0 = Sunday, 6 = Saturday
const isBusinessHours = (day >= 1 && day <= 5) && (hour >= 9 && hour <= 17);
return [{
json: {
timestamp: now.toISOString(),
isBusinessHours: isBusinessHours,
routeTo: isBusinessHours ? 'live_support' : 'automated_response'
}
}];
Common Conditional Logic Mistakes
Mistake 1: Not handling empty or null values Always check if data exists before evaluating it:
// Wrong
if ($json.revenue > 100000) // Fails if revenue is undefined
// Right
if ($json.revenue && $json.revenue > 100000)
Mistake 2: Case sensitivity issues Normalize text data before comparisons:
// Use toLowerCase() for consistent comparisons
const industry = ($json.industry || '').toLowerCase();
if (industry === 'technology') // More reliable
Mistake 3: Overly complex single conditions Break complex logic into smaller, testable pieces rather than creating massive conditional statements.
Testing Your Conditional Logic
Use Test Data Sets: Create test cases covering:
- Happy path scenarios
- Edge cases (empty fields, extreme values)
- Invalid data formats
- Missing required fields
Debug with Set Nodes: Add Set nodes after conditional branches to log which path was taken and why:
return [{
json: {
original_data: $json,
decision_path: 'enterprise_route',
reason: 'Company size > 500 and budget > $50k',
timestamp: new Date().toISOString()
}
}];
Performance Considerations
Minimize API Calls in Conditions: If your conditional logic requires external data, fetch it once and store it rather than making repeated API calls in different IF nodes.
Use Early Returns: Structure your logic so the most common cases are handled first, reducing unnecessary processing for the majority of your data.
Consider Batch Processing: For high-volume workflows, group similar conditional operations together rather than processing items individually.
Real-World Implementation Example
Here’s a complete customer lifecycle workflow using advanced conditional logic:
New Customer Processing:
- Data Validation: Check for required fields, clean data formats
- Customer Segmentation: Small business vs. enterprise based on multiple factors
- Onboarding Path Selection: Different sequences for different customer types
- Success Team Assignment: Route to appropriate customer success manager
- Billing Setup: Configure billing frequency and payment terms based on customer tier
- Integration Requirements: Automatically set up different tool integrations based on customer needs
Each step uses sophisticated conditional logic to ensure customers get exactly the right treatment for their situation.
Moving Beyond Basic Automation
Mastering conditional logic transforms your n8n workflows from simple task automation into intelligent business process engines. You can handle complex scenarios automatically, provide personalized experiences at scale, and build workflows that make smart decisions without human intervention.
The key is starting simple and gradually adding complexity as you identify patterns in your business processes. Every conditional branch should solve a real business problem and be thoroughly tested with actual data scenarios.
As you build more sophisticated conditional logic, you’ll find that your workflows become powerful tools for scaling personalized customer experiences and complex business operations.