The IF node in n8n allows you to create conditional workflows by evaluating conditions and directing the flow of data based on the results. With the IF node, you can define specific conditions for your workflow data and create different execution paths based on whether those conditions are met or not. This is essential for building intelligent workflows that can make decisions based on data values.
Step 1: Adding the IF Node to Your Workflow
To get started with the IF node in n8n, you first need to add it to your workflow. Here's how:
- Open your n8n workflow editor.
- Click on the "+" button to add a new node.
- In the search bar, type "IF" and select the IF node from the list.
- The IF node will be added to your workflow and automatically connected to the previous node.
The IF node has three output connections:
- True: Data flows through this output if the condition is met.
- False: Data flows through this output if the condition is not met.
- Error: Data flows through this output if there's an error during evaluation.
Step 2: Configuring Basic Conditions
Once you've added the IF node to your workflow, you need to configure the conditions. Here's how to set up a basic condition:
- Click on the IF node to open its settings panel.
- In the "Conditions" section, you'll see options to configure your condition.
- Select a "Value 1" by clicking on the gears icon to access dynamic data from previous nodes.
- Choose an "Operation" (like equals, not equals, contains, larger, smaller, etc.).
- Set "Value 2" as the comparison value.
For example, to check if a user's age is greater than 18:
- Value 1: {{$json.user.age}}
- Operation: larger
- Value 2: 18
Step 3: Working with Multiple Conditions
The IF node allows you to create complex conditions with multiple criteria. Here's how to set up multiple conditions:
- In the IF node settings, find the "Add Condition" button below your first condition.
- Click on "Add Condition" to add a new condition line.
- Set up the new condition as needed.
- Choose how multiple conditions should be evaluated by selecting either:
- "ALL" - All conditions must be true (logical AND)
- "ANY" - At least one condition must be true (logical OR)
For example, to check if a user is both over 18 AND has a verified email:
- Condition 1:
- Value 1: {{$json.user.age}}
- Operation: larger
- Value 2: 18
- Condition 2:
- Value 1: {{$json.user.emailVerified}}
- Operation: equals
- Value 2: true
- Combination: ALL
Step 4: Using Nested Conditions with Condition Groups
For more complex logical evaluations, you can use condition groups to create nested conditions:
- In the IF node settings, click on "Add Condition Group."
- This creates a new group of conditions that can be evaluated separately.
- Configure the conditions within the group.
- Choose the "Combination Mode" within the group (ALL or ANY).
- Set the relationship between groups using the main "Combination Mode."
For example, to check if (age > 18 AND country = "US") OR (age > 21):
- Group 1:
- Condition: {{$json.user.age}} larger 18
- Condition: {{$json.user.country}} equals "US"
- Combination: ALL
- Group 2:
- Condition: {{$json.user.age}} larger 21
- Main Combination: ANY
Step 5: Using Advanced Operators
The IF node supports various operators for different data types. Here are some key operators:
For text/string comparisons:
- equals: Check if values match exactly
- not equals: Check if values don't match
- contains: Check if one string contains another
- not contains: Check if one string doesn't contain another
- starts with: Check if a string starts with specific text
- ends with: Check if a string ends with specific text
- regex: Use regular expressions for complex pattern matching
For numeric comparisons:
- larger: Greater than
- larger or equal: Greater than or equal to
- smaller: Less than
- smaller or equal: Less than or equal to
For boolean/existence checks:
- empty: Check if a value is empty
- not empty: Check if a value is not empty
- is null: Check if a value is null
- is not null: Check if a value is not null
Example using regex for email validation:
- Value 1: {{$json.user.email}}
- Operation: regex
- Value 2: ^[\w-.]+@([\w-]+.)+[\w-]{2,4}$
Step 6: Handling Different Data Types
The IF node can handle different data types, but it's important to ensure proper comparison:
- For string comparisons, use quotes around text values: "example"
- For numbers, enter the value directly without quotes: 42
- For booleans, use true or false without quotes
- For null checks, use null without quotes
- For dates, use proper date format or timestamp
Example comparing dates:
- Value 1: {{$json.order.date}}
- Operation: larger
- Value 2: 2023-01-01T00:00:00Z
Step 7: Using Data from Previous Nodes
The real power of the IF node comes from evaluating dynamic data from previous nodes:
- To access data from previous nodes, click the gears icon next to "Value 1" or "Value 2".
- This opens the Expression Editor where you can select variables from previous nodes.
- Navigate through the available data using the variable picker.
- Select the specific data field you want to use in your condition.
Common ways to access data:
- {{$json.fieldName}}: Access a field in the current item
- {{$node["NodeName"].json.fieldName}}: Access a field from a specific node
- {{$item(0).json.fieldName}}: Access a field from the first item in a list
Step 8: Connecting Nodes to True and False Outputs
After setting up your IF node conditions, you need to connect different workflow paths for true and false results:
- Add nodes that should execute when the condition is true.
- Connect these nodes to the "True" output of the IF node.
- Add nodes that should execute when the condition is false.
- Connect these nodes to the "False" output of the IF node.
For example:
- IF condition: Check if customer is premium
- True path: Send special offer email (connect to "True" output)
- False path: Send standard newsletter (connect to "False" output)
Step 9: Merging Conditional Paths with Merge Node
Often, you'll want to bring together the different conditional paths later in your workflow:
- Add a Merge node after your conditional paths.
- Connect both the true path's final node and the false path's final node to the Merge node.
- Configure the Merge node as needed (typically using "Append" mode to combine data).
This creates a workflow pattern like:
- Start → IF → True path → Merge → Continue workflow
- → IF → False path → Merge ↗
Step 10: Nested IF Nodes for Complex Decision Trees
For more complex decision making, you can nest multiple IF nodes:
- Add an IF node to your workflow for the first condition.
- Add another IF node connected to the "True" output of the first IF node.
- Add processing nodes for each possible path.
- Continue nesting IF nodes as needed for your decision tree.
For example, a customer classification workflow:
- IF 1: Is customer active? (True/False)
- IF 2 (on True path): Has premium subscription? (True/False)
- IF 3 (on False path): Has opened emails recently? (True/False)
Step 11: Using JavaScript in IF Conditions
For more advanced conditions, you can use JavaScript expressions:
- In the IF node settings, select "JavaScript Code" condition type.
- Write a JavaScript expression that returns true or false.
- Access node data using the built-in variables and methods.
Example JavaScript condition:
// Check if user has made a purchase in the last 30 days
const lastPurchaseDate = new Date($json.user.lastPurchaseDate);
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
return lastPurchaseDate > thirtyDaysAgo;
Step 12: Testing and Debugging IF Conditions
Properly testing your IF conditions is crucial:
- Use the "Execute Node" feature to test just the IF node.
- Examine the output in the "Execution Results" panel.
- Look for the "path" property in the results to see which output path was chosen.
- If using complex conditions, test with different input data to verify all paths work.
- Use console.log() in JavaScript conditions to debug complex logic.
For example, to debug a JavaScript condition:
// Debug complex condition
console.log("User age:", $json.user.age);
console.log("User country:", $json.user.country);
const isAdult = $json.user.age >= 18;
const isUSCitizen = $json.user.country === "US";
console.log("Is adult:", isAdult);
console.log("Is US citizen:", isUSCitizen);
return isAdult && isUSCitizen;
Step 13: Handling Arrays with IF Nodes
When working with arrays of data, the IF node evaluates each item separately:
- If your previous node outputs multiple items (an array), the IF node processes each item.
- Each item is evaluated against your conditions independently.
- Items that meet the condition go to the "True" output path.
- Items that don't meet the condition go to the "False" output path.
For array filtering:
- Configure your IF node condition (e.g., {{$json.price}} larger 100)
- All items where price > 100 will flow through the "True" path
- All items where price ≤ 100 will flow through the "False" path
Step 14: Using Environment Variables in Conditions
For more flexible workflows, you can use environment variables in your conditions:
- Set up environment variables in your n8n instance.
- Access them in your IF node using the $env variable.
- Use them in your conditions for configurable workflows.
Example:
- Value 1: {{$json.transaction.amount}}
- Operation: larger
- Value 2: {{$env.LARGE_TRANSACTION_THRESHOLD}}
Step 15: Common Use Cases and Patterns
Here are some common patterns and use cases for the IF node:
Data filtering: Route data based on specific criteria
- Condition: {{$json.status}} equals "active"
- True path: Process active items
- False path: Ignore or archive inactive items
Error handling: Check for potential issues before processing
- Condition: {{$json.data}} is not null
- True path: Process the data normally
- False path: Send error notification
Conditional notifications: Send alerts based on thresholds
- Condition: {{$json.metrics.errorRate}} larger 5
- True path: Trigger alert to team
- False path: Continue normal monitoring
Business rules implementation: Encode business logic
- Condition: {{$json.customer.totalSpent}} larger 1000
- True path: Apply VIP discount
- False path: Apply standard pricing
Step 16: Performance Considerations
When using IF nodes in complex workflows, consider these performance tips:
- Place IF nodes early in workflows to avoid unnecessary processing.
- Use IF nodes to filter out data that doesn't need further processing.
- For large datasets, consider using the Filter node instead of IF for simple filtering.
- Avoid overly complex JavaScript conditions for better performance.
- When using multiple nested IF nodes, consider if a Switch node might be more efficient.
Step 17: Combining IF with Switch Nodes
For workflows with multiple possible outcomes, consider using the Switch node alongside IF nodes:
- Use IF nodes for binary (yes/no) decisions.
- Use Switch nodes when you have multiple possible paths based on a single value.
- Create workflows that combine both for efficient decision trees.
For example:
- IF node: Check if order is valid
- Switch node (on True path): Route order based on product category
- Error handling (on False path): Handle invalid orders
Step 18: Real-World Example: Customer Segmentation
Let's build a complete example of using IF nodes for customer segmentation:
- Start with a node that retrieves customer data.
- Add an IF node to check for high-value customers:
- Condition: {{$json.lifetime\_value}} larger 1000
- On the True path, add another IF node to check engagement:
- Condition: {{$json.days_since_last\_purchase}} smaller 30
- Create paths for:
- High-value active customers (VIP treatment)
- High-value inactive customers (re-engagement campaign)
- Low-value customers (standard treatment)
Code for a more complex segmentation using JavaScript:
// Customer segmentation logic
const ltv = $json.lifetime\_value || 0;
const daysSinceLastPurchase = $json.days_since_last\_purchase || 999;
const purchaseCount = $json.purchase\_count || 0;
// VIP customer check
if (ltv > 1000 && daysSinceLastPurchase < 60) {
return true; // Route to VIP path
}
// Potential VIP check
if (ltv > 500 && purchaseCount > 5 && daysSinceLastPurchase < 90) {
return true; // Route to potential VIP path
}
return false; // Standard customer path
Step 19: Troubleshooting Common Issues
Here are solutions to common issues with IF nodes:
Condition not evaluating as expected:
- Check data types (strings vs numbers)
- Verify variable names and paths
- Use console.log() to debug values
- Check for null or undefined values
No data flowing through True/False paths:
- Ensure previous nodes are returning data
- Check if condition logic is correct
- Verify connections between nodes
Issues with array data:
- Remember that IF nodes process each array item separately
- Use Item Lists node if you need to process the entire array as one
Data type conversion issues:
- Use parseInt() or parseFloat() for number conversions
- Use toString() for string conversions
- Use Boolean() for boolean conversions
Example for handling number comparison issues:
// Convert string to number for comparison
const price = parseFloat($json.price);
const threshold = 100;
// Check for valid number before comparison
if (isNaN(price)) {
console.log("Invalid price value:", $json.price);
return false;
}
return price > threshold;
Step 20: Advanced Tips and Best Practices
To master the IF node in n8n, consider these advanced tips:
Use descriptive node names for clarity:
- Rename your IF nodes to describe their purpose (e.g., "Check If Premium Customer")
- This makes complex workflows more understandable
Document complex conditions:
- Add notes nodes before complex IF nodes to explain the logic
- Use comments in JavaScript code conditions
Design for maintainability:
- Avoid overly complex nested conditions
- Consider extracting complex logic to Function nodes
- Use environment variables for configurable thresholds
Testing strategies:
- Create test workflows with known inputs to verify IF node behavior
- Test edge cases (null values, empty strings, extreme numbers)
- Use the Debug node to monitor data at different points in the workflow
Error handling:
- Connect error handling nodes to the "Error" output of IF nodes
- Use try/catch blocks in JavaScript conditions
- Validate input data before evaluation
Example of robust error handling in JavaScript condition:
// Robust condition with error handling
try {
// Check if necessary data exists
if (!$json.user || typeof $json.user !== 'object') {
console.log("Missing user data:", $json);
return false;
}
// Safely access nested properties
const age = $json.user.age || 0;
const subscriptionLevel = $json.user.subscription?.level || "free";
// Business logic
if (age >= 18 && subscriptionLevel === "premium") {
return true;
}
return false;
} catch (error) {
console.log("Error in condition evaluation:", error.message);
return false;
}
By following this comprehensive guide, you should now have a thorough understanding of how to use the IF node in n8n workflows, from basic conditions to advanced scenarios with complex decision logic.