# Code in JavaScript

> Execute custom JavaScript code within the workflow.

Source: https://docs.sommatic.ai/en/nodes/code.js/

- Slug: `code.js`
- Family: Code
- Version: 1.0.0
- Status: Available
- Execution: async

Execute custom JavaScript code within the workflow.

Write JavaScript to transform data, implement custom logic, or perform calculations. The incoming payload is available as `$json` and common helpers like lodash (`_`) are pre-loaded.

**Execution Modes:**
- **Sandbox** (default): Fast, isolated execution via VM context. No I/O access (no `require`, no `fs`, no `process`). Ideal for data transformations and calculations.
- **Process**: Full Node.js execution in a child process. Supports `require()` for installed modules and I/O operations. Use for advanced integrations.

**Convention:** Your code must return a value. The returned value becomes the node output.

**Examples:**
- `return $json.items.map(i => i.name)`
- `const total = $json.prices.reduce((sum, p) => sum + p, 0); return { total }`
- `return _.groupBy($json.users, 'role')`

## Configuration

- `code` (string, required): JavaScript code to execute. Use $json to access input data. Must return a value.

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

- `out` (default): Code executed successfully.
- `error`: Syntax error, runtime error, or timeout.

## Input contract

- `payload` (object, optional)

## Output contract

- `result` (object, optional): The value returned by the code.
- `logs` (array<string>, optional): Console.log outputs captured during execution.

## In expressions

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

- `$("Code in JavaScript").item.json.result` (object) = `{…}`: The value returned by the code.
- `$("Code in JavaScript").item.json.logs` (array) = `[…] (1)`: Console.log outputs captured during execution.
- `$("Code in JavaScript").item.json.result.total` (number) = `742.5` (Not suggested by the editor)
- `$("Code in JavaScript").item.json.result.count` (number) = `3` (Not suggested by the editor)


## How it works

Runs your JavaScript as the body of an async function, with the node input as `$json`, and returns `{ result, logs }`: the value you `return` and the captured console lines.

1. Resolves the config. `{{ }}` inside `code` is evaluated as an expression before the code runs, like any other config value.
2. Fails through `error` with `No code provided` when `code` is empty.
3. Picks the mode from `execution.mode` (default `sandbox`) and the limit from `execution.timeout_ms` (default 5000 ms).
4. Exposes the input payload (the previous node's output) as `$json`, and as `$input.item`, `$input.first()`, `$input.last()` and `$input.all()` (a one-element array). Unlike in expressions, `$input.item` is the payload itself, not `{ json }`.
5. Runs the code wrapped as `(async () => { <code> })()`, so `await` works and you must `return` the output.
6. Returns `{ result, logs }` through `out`: `result` is the returned value (`null` when nothing is returned) and `logs` the captured `console.log`/`warn`/`error` lines.

## In a workflow

### Node

```json
{
  "node_id": "node-sum-items",
  "label": "Sum items",
  "operator_slug": "code.js",
  "operator_version": "1.0.0",
  "config": {
    "code": "const items = $json.items || [];\nconsole.log(`processing ${items.length} items`);\nreturn { total: _.sumBy(items, 'amount'), count: items.length };",
    "execution": {
      "mode": "sandbox",
      "timeout_ms": 5000
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "result": {
      "total": 742.5,
      "count": 3
    },
    "logs": [
      "processing 3 items"
    ]
  },
  "port": "out"
}
```

## Output ports (behaviour in the code)

### `out`

The code finished without throwing. Downstream nodes read your value as `$json.result`.

```json
{
  "result": {
    "total": 742.5,
    "count": 3
  },
  "logs": [
    "processing 3 items"
  ]
}
```

### `error`

The code threw, had a syntax error or timed out. Data is `{ error, stack, logs }`, or `{ error: "TIMEOUT", logs }` on a sandbox timeout. With empty `code` the envelope has no `data`, so the next node receives `{ ok: false, errors: ["No code provided"], port: "error" }`.

```json
{
  "error": "Cannot read properties of undefined (reading 'map')",
  "stack": "TypeError: Cannot read properties of undefined (reading 'map')\n    at code.js:1:31",
  "logs": []
}
```

## Behaviour in the code

- `execution.mode`: `sandbox` (default): an isolated V8 context with `$json`, `$input`, `console`, `_` (lodash), `JSON`, `Math`, `Date`, `String`, `Number`, `Boolean`, `Array`, `Object`, `RegExp`, `Map`, `Set`, `Promise`, `parseInt`, `parseFloat`, `isNaN`, `isFinite` and the URI encode/decode functions. `process`: a separate Node.js process where built-in modules can be required and `_` is lodash; packages of the orchestrator are not resolvable by bare name.
- `execution.timeout_ms`: Default 5000 ms in the code. The schema shows 300000 because the generic execution settings override the field's default; the code does not apply that value.
- `code`: Avoid writing `{{` in your code (for example in template strings or object literals written as `{{`): it is resolved as an expression before execution.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `No code provided` | `error` | `code` is empty or not a string. |
| `Script timed out after <timeout_ms>ms` | `error` | Sandbox mode: the script ran longer than `execution.timeout_ms`; `data.error` is `TIMEOUT`. Raise the limit or reduce the work. In process mode a timeout stops the child process and the message is its stderr, or `No output`. |
| `<name> is not defined` | `error` | Sandbox mode exposes only the listed globals: `require`, `process`, `Buffer`, `setTimeout` and `fetch` are not available there. Use `execution.mode: "process"` when you need Node.js APIs. |

## Notes and limits

- `console.log` arguments are converted with `String()`: objects appear as `[object Object]`. Log `JSON.stringify(value)` instead.
- Process mode: the child process receives only locale, path and proxy environment variables, its input travels through a temporary file that is removed after the run, and the returned value must be JSON-serializable.
- Each run starts from a clean context: nothing persists between runs or between nodes.


## Contracts (JSON Schema)

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

```json
{
  "slug": "code.js",
  "name": "Code in JavaScript",
  "category": "code",
  "version": "1.0.0",
  "description": "Execute custom JavaScript code within the workflow.\n\n  Write JavaScript to transform data, implement custom logic, or perform calculations. The incoming payload is available as `$json` and common helpers like lodash (`_`) are pre-loaded.\n\n  **Execution Modes:**\n  - **Sandbox** (default): Fast, isolated execution via VM context. No I/O access (no `require`, no `fs`, no `process`). Ideal for data transformations and calculations.\n  - **Process**: Full Node.js execution in a child process. Supports `require()` for installed modules and I/O operations. Use for advanced integrations.\n\n  **Convention:** Your code must return a value. The returned value becomes the node output.\n\n  **Examples:**\n  - `return $json.items.map(i => i.name)`\n  - `const total = $json.prices.reduce((sum, p) => sum + p, 0); return { total }`\n  - `return _.groupBy($json.users, 'role')`",
  "capabilities": [
    "code",
    "javascript",
    "transform",
    "logic"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "code": {
        "type": "string",
        "title": "Code",
        "description": "JavaScript code to execute. Use $json to access input data. Must return a value.",
        "ui_widget": "code_editor",
        "ui_options": {
          "language": "javascript"
        }
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "mode": {
            "type": "string",
            "enum": [
              "sandbox",
              "process"
            ],
            "default": "sandbox",
            "title": "Execution Mode",
            "description": "Sandbox: fast, no I/O, isolated VM. Process: full Node.js with require() support."
          },
          "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
          },
          "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
          }
        }
      }
    },
    "required": [
      "code"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "description": "Any JSON payload. Accessible as $json inside the code.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "result": {
        "type": "object",
        "description": "The value returned by the code."
      },
      "logs": {
        "type": "array",
        "items": {
          "type": "string"
        },
        "description": "Console.log outputs captured during execution."
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Result",
      "description": "Code executed successfully.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Syntax error, runtime error, or timeout."
    }
  ],
  "execution_mode": "async",
  "tags": [
    "code",
    "javascript",
    "transform",
    "script"
  ],
  "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",
  "properties": {
    "code": {
      "type": "string",
      "title": "Code",
      "description": "JavaScript code to execute. Use $json to access input data. Must return a value.",
      "ui_widget": "code_editor",
      "ui_options": {
        "language": "javascript"
      }
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "mode": {
          "type": "string",
          "enum": [
            "sandbox",
            "process"
          ],
          "default": "sandbox",
          "title": "Execution Mode",
          "description": "Sandbox: fast, no I/O, isolated VM. Process: full Node.js with require() support."
        },
        "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
        },
        "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
        }
      }
    }
  },
  "required": [
    "code"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "description": "Any JSON payload. Accessible as $json inside the code.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "result": {
      "type": "object",
      "description": "The value returned by the code."
    },
    "logs": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "description": "Console.log outputs captured during execution."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Result",
    "description": "Code executed successfully.",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Syntax error, runtime error, or timeout."
  }
]
```
