# Switch (Route)

> Routes the execution flow to one of multiple ports based on a matching condition.

Source: https://docs.sommatic.ai/en/nodes/flow.switch/

- Slug: `flow.switch`
- Family: Flow control
- Version: 1.0.0
- Status: Available
- Execution: sync

Routes the execution flow to one of multiple ports based on a matching condition.

This operator functions similarly to a switch-case or if-else-if ladder. It evaluates a list of defined 'cases' in order. The first case whose expression evaluates to true triggers its corresponding output port. If no cases match, execution is routed to the 'default' port.

**Behavior:**
- **Sequential Evaluation:** Cases are checked in the order defined.
- **First Match:** By default, stops after the first true condition.
- **Default Path:** If no conditions are met, the 'default' port is activated.

**Use Cases:**
- Routing orders based on status (e.g., 'pending' -> Port A, 'shipped' -> Port B).
- Categorizing support tickets by priority.
- Handling different event types in a webhook.

## Configuration

- `cases` (array<object>, required): Define the conditions and their corresponding output ports.
- `first_match` (boolean, optional): If enabled, only the first matching port is activated. If disabled, all matching ports are activated (multicast). Default: `true`.

Its configuration shows the shared execution settings, but this node does not apply retries (`retryOnFail`, `maxTries`) yet. `continueOnFail` is not applied by any node.

## Output ports

- `default` (default): Activated when no cases match.
- `error`: Activated if an evaluation error occurs.

## Input contract

- `payload` (object, required)

## Output contract

- `payload` (object, optional)

## In expressions

What a later node can read from this node's output with `$("Switch (Route)").item.json.<path>` (write your node's label instead of `Switch (Route)`). **Editor** marks the paths the workflow editor suggests under Previous Nodes (the output contract); **Worker** marks the paths the worker really returns through `default`, from the output shown in Ports.

- `$("Switch (Route)").item.json.payload` (object) **The worker does not return it: reads as undefined.**
- `$("Switch (Route)").item.json.order_id` (string) = `"ord_125"` (Not suggested by the editor)
- `$("Switch (Route)").item.json.amount` (number) = `40` (Not suggested by the editor)
- `$("Switch (Route)").item.json.status` (string) = `"active"` (Not suggested by the editor)


## How it works

Evaluates routing cases in order and sends the unchanged payload through the port named by the first matching case, or through `default`.

1. Resolves the config: `{{ }}` in each case `expr` are evaluated by the Expression Engine.
2. If `cases` is not an array, the payload goes to `default`.
3. Skips a case whose `port` is empty or whose resolved `expr` is falsy (`false`, `0`, `""`, `undefined`).
4. A boolean `expr` is used as is; any other value is evaluated as JSONata against the payload (`amount > 1000`).
5. Collects the port of each truthy case and stops at the first one when `first_match` is true (default).
6. Sends the payload through the first matched port with `meta.matched` listing the matches, or through `default` when none matched.

## In a workflow

### Node

```json
{
  "node_id": "node-route-order",
  "label": "Route order",
  "operator_slug": "flow.switch",
  "operator_version": "1.0.0",
  "config": {
    "cases": [
      {
        "expr": "{{ $json.amount > 1000 }}",
        "port": "high_value"
      },
      {
        "expr": "status = \"on_hold\"",
        "port": "on_hold"
      }
    ],
    "first_match": true
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "order_id": "ord_123",
    "amount": 1250,
    "status": "active"
  },
  "port": "high_value",
  "meta": {
    "matched": [
      "high_value"
    ]
  }
}
```

## Output ports (behaviour in the code)

### `default`

No case matched, or `cases` is not an array. A matching case sends the same payload through the port named in that case instead.

```json
{
  "order_id": "ord_125",
  "amount": 40,
  "status": "active"
}
```

### `error`

A case could not be compiled or evaluated as JSONata.

```json
{
  "ok": false,
  "errors": [
    "Switch evaluation error: <JSONata message>"
  ],
  "port": "error"
}
```

## Behaviour in the code

- `cases`: Each case is `{ expr, port }`. The case port is a free name (`^[a-z0-9_-]+$`) that must match the `from.port` of an edge; a matched port without an edge ends the branch. The definition example `$json.amount > 1000` without `{{ }}` never matches, because `$json` is not bound in JSONata: write `amount > 1000` or `{{ $json.amount > 1000 }}`.
- `first_match`: With false, every case is evaluated and listed in `meta.matched`, but only the first matched port fires: there is no multicast.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Switch evaluation error: <JSONata message>` | `error` | A case `expr` is invalid JSONata. Cases after an earlier match are not evaluated when `first_match` is true. |
| `Switch evaluation error: path.charAt is not a function` | `error` | A case `{{ }}` returned a non-zero number, an object or an array. Return a boolean. |

## Notes and limits

- An edge whose `from.port` is `*` receives the payload whatever port fires.
- `meta` is recorded in the run steps only: downstream nodes receive `data` as their payload and cannot read `meta` through `$json` or `$("Node")`.
- When the envelope has no `data` (or `data` is falsy), the engine stores the whole envelope as the node output: on `error` the next node receives `{ ok: false, errors: [...], port: "error" }` as its payload.


## Contracts (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "flow.switch",
  "name": "Switch (Route)",
  "category": "flow",
  "version": "1.0.0",
  "description": "Routes the execution flow to one of multiple ports based on a matching condition.\n\n  This operator functions similarly to a switch-case or if-else-if ladder. It evaluates a list of defined 'cases' in order. The first case whose expression evaluates to true triggers its corresponding output port. If no cases match, execution is routed to the 'default' port.\n\n  **Behavior:**\n  - **Sequential Evaluation:** Cases are checked in the order defined.\n  - **First Match:** By default, stops after the first true condition.\n  - **Default Path:** If no conditions are met, the 'default' port is activated.\n\n  **Use Cases:**\n  - Routing orders based on status (e.g., 'pending' -> Port A, 'shipped' -> Port B).\n  - Categorizing support tickets by priority.\n  - Handling different event types in a webhook.",
  "capabilities": [
    "branching",
    "logic",
    "jsonata",
    "router"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "cases"
    ],
    "properties": {
      "cases": {
        "type": "array",
        "title": "Routing Cases",
        "description": "Define the conditions and their corresponding output ports.",
        "items": {
          "type": "object",
          "properties": {
            "expr": {
              "type": "string",
              "title": "Condition Expression",
              "format": "expression",
              "description": "Expression that must evaluate to true. Use the Expression Editor for JavaScript with full variable access, or enter raw JSONata without {{ }} (see jsonata.org). Example: $json.amount > 1000"
            },
            "port": {
              "type": "string",
              "title": "Output Port Name",
              "description": "The name of the port to signal if this case matches (e.g., \"high_value\").",
              "pattern": "^[a-z0-9_-]+$"
            }
          },
          "required": [
            "expr",
            "port"
          ]
        }
      },
      "first_match": {
        "type": "boolean",
        "title": "Stop on First Match",
        "default": true,
        "description": "If enabled, only the first matching port is activated. If disabled, all matching ports are activated (multicast)."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "description": "The JSON payload to be evaluated against the switch cases.",
    "properties": {
      "payload": {
        "type": "object"
      }
    },
    "required": [
      "payload"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "description": "The original payload is passed through to the matched output port(s).",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "default",
      "label": "Default",
      "is_default": true,
      "description": "Activated when no cases match."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Activated if an evaluation error occurs."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "logic",
    "router",
    "multi-path",
    "conditional"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "cases"
  ],
  "properties": {
    "cases": {
      "type": "array",
      "title": "Routing Cases",
      "description": "Define the conditions and their corresponding output ports.",
      "items": {
        "type": "object",
        "properties": {
          "expr": {
            "type": "string",
            "title": "Condition Expression",
            "format": "expression",
            "description": "Expression that must evaluate to true. Use the Expression Editor for JavaScript with full variable access, or enter raw JSONata without {{ }} (see jsonata.org). Example: $json.amount > 1000"
          },
          "port": {
            "type": "string",
            "title": "Output Port Name",
            "description": "The name of the port to signal if this case matches (e.g., \"high_value\").",
            "pattern": "^[a-z0-9_-]+$"
          }
        },
        "required": [
          "expr",
          "port"
        ]
      }
    },
    "first_match": {
      "type": "boolean",
      "title": "Stop on First Match",
      "default": true,
      "description": "If enabled, only the first matching port is activated. If disabled, all matching ports are activated (multicast)."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "description": "The JSON payload to be evaluated against the switch cases.",
  "properties": {
    "payload": {
      "type": "object"
    }
  },
  "required": [
    "payload"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "The original payload is passed through to the matched output port(s).",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "default",
    "label": "Default",
    "is_default": true,
    "description": "Activated when no cases match."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Activated if an evaluation error occurs."
  }
]
```
