On this page
Sommatic Docs
Open portal

Code in JavaScript

Execute custom JavaScript code within the workflow.

View as Markdown
Open in
Code Available code.js Version 1.0.0 Execution: async

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.

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')

How it works

  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

The node as it appears in a workflow file (draft_nodes[]), and the envelope of a successful run.

{
  "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
    }
  }
}

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.

Behaviour in the code

What the implementation does with these keys beyond what the schema says.

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.

Output ports

out default

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

Data
{
  "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" }.

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

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.

ExpressionEditorWorker
$("Code in JavaScript").item.json.resultobject= {…}The value returned by the code.
$("Code in JavaScript").item.json.logsarray= […] (1)Console.log outputs captured during execution.
$("Code in JavaScript").item.json.result.totalnumberNot suggested by the editor= 742.5—
$("Code in JavaScript").item.json.result.countnumberNot suggested by the editor= 3—

— Worker: The worker returns it but the editor does not suggest it: write it by hand. Keys inside objects can depend on your data or configuration (for example one key per label).

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.

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.

Contracts (JSON Schema)

The definition exactly as the orchestrator declares it. All is the whole *.definition.js; compare it with the sections above to spot differences between the documentation and the schema. Use it to validate a node before you publish.

{
  "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
    }
  }
}

Execution

Execution
async
Stateful
No
Retries (retryOnFail)
No
Capabilities
codejavascripttransformlogic
Tags
codejavascripttransformscript

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.

Reviewed against the orchestrator code · 31e874b · 2026-11-26

Install agent tools

Give your coding agent the official Sommatic AI docs: skills, the docs MCP server and Markdown pages, so it never has to scrape the site.

Skills only. They do not update by themselves; run it again to refresh.

npx skills add https://docs.sommatic.ai
How agents read these docs