BlocksFlow control

switch

Route a message to one or more outputs by comparing a property against rules.

Overview

The switch block checks a selected property and sends the incoming message to every output whose rule matches.

In the editor, you configure:

  • property: the value to test
  • propertyType: msg, flow, global, jsonata, or env
  • rules: one output per rule
  • checkall: check all rules or stop after the first match
  • repair: recreate sequence metadata when routing message sequences

Supported rule types

Value rules

  • ==
  • !=
  • <
  • <=
  • >
  • >=
  • between
  • contains
  • regex
  • has key
  • true
  • false
  • null
  • not null
  • empty
  • not empty
  • is of type

Sequence rules

  • head
  • index
  • tail

These use msg.parts from sequence-aware nodes.

Other rules

  • JSONata expression
  • otherwise

How matching works

  • The original message is forwarded to each matching output.
  • If checkall is set to stop on first match, evaluation ends after the first matching rule.
  • If no rules match and there is no otherwise rule, the node sends nothing.
  • is true, is false, and is null are strict checks.
  • empty and not empty work for strings, arrays, buffers, and objects.

Message sequences

When repair is off, the node keeps the original msg.parts values.

When repair is on, the node buffers the whole incoming sequence and creates new sequence metadata for each matching output. This is mainly useful when you want each routed branch to behave like its own clean sequence.

Inputs

The block accepts any incoming message. The property you configured determines what gets tested.

Example input

{
  "payload": {
    "status": "approved",
    "score": 0.92
  },
  "topic": "review"
}

Outputs

The block does not change msg.payload by itself. It routes the original message to one or more outputs.

Example configuration

  • property: msg.payload.status
  • rules:
    • == "approved"
    • == "rejected"
    • otherwise

Output behavior

  • If msg.payload.status is "approved", the message is sent to output 1.
  • If it is "rejected", the message is sent to output 2.
  • Otherwise, the message is sent to output 3.

Examples

Route by status

Property:

msg.payload.status

Rules:

1. == "approved"
2. == "rejected"
3. otherwise

Route by score

Property:

msg.payload.score

Rules:

1. >= 0.9
2. >= 0.7
3. otherwise

Route by data type

Property:

msg.payload.items

Rules:

1. is of type array
2. is of type object
3. otherwise

Limitations

  • Each rule creates a separate output.
  • Complex JSONata rules can be slower than simple property checks.
  • Sequence repair buffers messages, so it can increase memory usage for large sequences.

Common mistakes

  • Using the wrong property type for the field you want to test.
  • Expecting switch to modify the message content instead of just routing it.
  • Forgetting an otherwise rule when unmatched messages still need handling.
  • Using repair on large sequences without considering buffering cost.

title: switch description: Route messages to different outputs based on conditions and rules

switch Block

The switch block routes messages based on their property values or sequence position.

Overview

When a message arrives, the node will evaluate each of the defined rules and forward the message to the corresponding outputs of any matching rules.

Optionally, the node can be set to stop evaluating rules once it finds one that matches.

The rules can be evaluated against an individual message property, a flow or global context property, environment variable or the result of a JSONata expression.

Rules

There are four types of rule:

  • Value rules are evaluated against the configured property
  • Sequence rules can be used on message sequences, such as those generated by the Split node
  • JSONata Expression can be provided that will be evaluated against the whole message and will match if the expression returns a true value.
  • Otherwise rule can be used to match if none of the preceding rules have matched.

Notes

The is true/false and is null rules perform strict comparisons against those types. They do not convert between types.

The is empty and is not empty rules can be used to test the length of Strings, Arrays and Buffers, or the number of properties an Object has. Neither rule will pass if the property being tested has a boolean, null or undefined value.

Handling Message Sequences

By default, the node does not modify the msg.parts property of messages that are part of a sequence.

The recreate message sequences option can be enabled to generate new message sequences for each rule that matches. In this mode, the node will buffer the entire incoming sequence before sending the new sequences on. The runtime setting nodeMessageBufferMaxLength can be used to limit how many messages nodes will buffer.

Configuration Options

Property to Test

  • msg.payload: Test the message payload (default)
  • msg.topic: Test the message topic
  • msg.filename: Test filename property
  • Custom Property: Test any message property (e.g., msg.headers.content-type)
  • JSONata Expression: Use JSONata for complex property access

Rule Types

  • ==: Equals (string comparison)
  • !=: Not equals
  • <: Less than (numeric comparison)
  • <=: Less than or equal
  • >: Greater than
  • >=: Greater than or equal
  • between: Between two values (inclusive)
  • contains: String contains substring
  • regex: Regular expression match
  • true: Property is true
  • false: Property is false
  • null: Property is null
  • not null: Property is not null
  • empty: Property is empty (string, array, or object)
  • not empty: Property is not empty
  • is of type: Check data type (string, number, boolean, array, object)

Output Configuration

  • Multiple Rules: Add multiple rules with corresponding outputs
  • Rule Order: Rules are evaluated in order from top to bottom
  • Stop on First Match: Stop evaluation after first matching rule
  • Continue on All Matches: Send to all matching outputs

Common Use Cases

Document Type Routing

Route documents based on classification results:

// Test msg.payload.document_type
Rules:
1. == "invoice" -> Output 1 (Invoice Processing)
2. == "contract" -> Output 2 (Contract Analysis)
3. == "receipt" -> Output 3 (Receipt Processing)
4. otherwise -> Output 4 (Manual Review)

Confidence-Based Processing

Route based on AI confidence scores:

// Test msg.payload.confidence
Rules:
1. >= 0.9 -> Output 1 (Auto Process)
2. >= 0.7 -> Output 2 (Quick Review)
3. >= 0.5 -> Output 3 (Full Review)
4. < 0.5 -> Output 4 (Reject/Manual)

File Type Handling

Process different file types appropriately:

// Test msg.filename
Rules:
1. regex: \.pdf$ -> Output 1 (PDF Processor)
2. regex: \.(jpg|jpeg|png|tiff)$ -> Output 2 (Image OCR)
3. regex: \.csv$ -> Output 3 (CSV Parser)
4. otherwise -> Output 4 (Unsupported Format)

Error Handling

Route based on processing results:

// Test msg.payload.status
Rules:
1. == "success" -> Output 1 (Continue Processing)
2. == "warning" -> Output 2 (Log Warning)
3. == "error" -> Output 3 (Error Handler)
4. == "retry" -> Output 4 (Retry Logic)

Rule Examples

Basic Comparisons

// Numeric comparisons
msg.payload.amount > 1000;

// String comparisons
msg.payload.status == "completed";

// Boolean checks
msg.payload.urgent == true;

Advanced Patterns

// Regular expressions
msg.filename matches /^invoice_\d{8}\.pdf$/

// Contains checks
msg.payload.description contains "urgent"

// Type checking
msg.payload.items is of type "array"

// Range checking
msg.payload.score between 80 and 100

Complex Conditions

// Using JSONata expressions
$exists(payload.customer.email) and payload.amount > 500

// Nested property access
msg.payload.metadata.processing.status == "complete"

// Array operations
$count(payload.items) > 0

Multiple Output Patterns

Exclusive Routing (Stop on First Match)

Input -> Switch -> Output 1: High Priority
              -> Output 2: Medium Priority
              -> Output 3: Low Priority
              -> Output 4: Default

Inclusive Routing (Continue on All Matches)

Input -> Switch -> Output 1: Log All
              -> Output 2: Process Urgent
              -> Output 3: Notify Errors
              -> Output 4: Archive

Flow Examples

Document Processing Pipeline

Document -> Document Classifier -> Switch:
                                 ├─ Invoice -> Invoice Processor
                                 ├─ Contract -> Contract Analyzer
                                 ├─ Receipt -> Receipt Processor
                                 └─ Unknown -> Manual Review

Quality Control Workflow

OCR Results -> Switch (by confidence):
              ├─ High (>0.9) -> Auto Approve
              ├─ Medium (0.7-0.9) -> Quick Review
              ├─ Low (0.5-0.7) -> Full Review
              └─ Very Low (<0.5) -> Reject

Multi-stage Processing

Input -> Switch (by type):
        ├─ PDF -> PDF Processor -> Switch (by pages):
        │                       ├─ Single -> Fast Process
        │                       └─ Multi -> Batch Process
        └─ Image -> Image Processor -> OCR

Error Recovery Pattern

Process -> Switch (by result):
          ├─ Success -> Continue
          ├─ Retry Error -> Delay -> Retry
          ├─ Temp Error -> Log -> Queue
          └─ Fatal Error -> Alert -> Stop

Best Practices

  1. Order Rules Carefully: Most specific rules first, general rules last
  2. Include Default Case: Always have an "otherwise" rule for unmatched cases
  3. Use Appropriate Operators: Choose the right comparison type for your data
  4. Test Edge Cases: Consider null, empty, and unexpected values
  5. Keep Rules Simple: Complex logic might be better in a function block

Common Patterns

Priority-Based Routing

// Test msg.payload.priority
Rules:
1. == "critical" -> Immediate Processing
2. == "high" -> Priority Queue
3. == "normal" -> Standard Queue
4. == "low" -> Batch Processing

Size-Based Processing

// Test msg.payload.file_size
Rules:
1. < 1000000 -> Fast Processing (< 1MB)
2. < 10000000 -> Standard Processing (< 10MB)
3. >= 10000000 -> Large File Processing (>= 10MB)

Time-Based Routing

// Test current time using JSONata
$hour($now()) between 9 and 17 -> Business Hours Processing
otherwise -> After Hours Queue

Multi-Condition Routing

// Complex conditions
(msg.payload.type == "urgent" and msg.payload.amount > 5000) -> Escalate
(msg.payload.customer_tier == "premium") -> Premium Processing
otherwise -> Standard Processing

Debugging Tips

  • Use debug blocks on each output to see which path messages take
  • Check message structure to ensure you're testing the right properties
  • Test with various input scenarios to validate all rules
  • Use the "otherwise" output to catch unexpected cases

Performance Considerations

  • Rules are evaluated in order - put most common matches first
  • Complex JSONata expressions can impact performance
  • Consider using multiple simple switches instead of one complex switch
  • Use "stop on first match" when appropriate to avoid unnecessary evaluations

Integration Examples

With Document Classification

// After document classification
Input: {
    payload: {
        classification: "invoice",
        confidence: 0.95,
        metadata: { pages: 2 }
    }
}

Switch Rules:
1. msg.payload.classification == "invoice" -> Invoice Flow
2. msg.payload.classification == "contract" -> Contract Flow

With File Processing

// File upload processing
Input: {
    payload: buffer,
    filename: "document.pdf",
    mimetype: "application/pdf"
}

Switch Rules:
1. msg.mimetype == "application/pdf" -> PDF Processing
2. msg.mimetype contains "image/" -> Image Processing

With Error Handling

// Processing result routing
Input: {
    payload: {
        result: "error",
        error_code: "TIMEOUT",
        retry_count: 2
    }
}

Switch Rules:
1. msg.payload.result == "success" -> Continue
2. msg.payload.error_code == "TIMEOUT" and msg.payload.retry_count < 3 -> Retry
3. otherwise -> Error Queue

Tips

  • Start with simple rules and add complexity gradually
  • Use descriptive output labels to make flows more readable
  • Consider the default case for any unmatched inputs
  • Test rules with edge cases and unexpected data types
  • Combine with other flow control blocks for sophisticated workflows

Use switch blocks with Function for complex logic and Debug to trace routing decisions.