> For the complete documentation index, see [llms.txt](https://docs.agenticflow.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.agenticflow.ai/reference/nodes/run_javascript.md).

# Run JavaScript

**Action ID:** `run_javascript`

## Description

Run JavaScript code to perform custom data transformations and logic. The code must define an `execute` function that receives workflow context and returns a result.

## Input Parameters

| Name  | Type   | Required | Default            | Description                                                                                                                                                                                                                                                                                                                                                                                                               |
| ----- | ------ | :------: | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| code  | string |     ✓    | (default template) | The Javascript code to execute, returning the value to use in the next node. Your code must define a function named `execute` that takes an object as an argument. The object will have the following properties: `input` (the input to the node), `workflow_run_input` (the input to the workflow run), `workflow_run_state` (the state of the workflow run). You can use the `log` function to print debug information. |
| input | object |     -    | {}                 | Input to the JavaScript code. Input will be available in the `args.input` object.                                                                                                                                                                                                                                                                                                                                         |

<details>

<summary>View JSON Schema</summary>

```json
{
  "description": "RunJavaScript node input.",
  "properties": {
    "code": {
      "title": "Code",
      "type": "string",
      "description": "The Javascript code to execute, returning the value to use in the next node.\n        Your code must define a function named `execute` that takes an object as an argument.\n        The object will have the following properties:\n        - `input`: The input to the node.\n        - `workflow_run_input`: The input to the workflow run.\n        - `workflow_run_state`: The state of the workflow run.\n        You can use the `log` function to print debug information. The output of the `log` function will be available in the `output` field of the node."
    },
    "input": {
      "default": {},
      "title": "Input",
      "type": "object",
      "description": "Input to the JavaScript code. Input will be available in the `args.input` object."
    }
  },
  "required": [
    "code"
  ],
  "title": "RunJavaScriptNodeInput",
  "type": "object"
}
```

</details>

## Output Parameters

| Name    | Type   | Description                        |
| ------- | ------ | ---------------------------------- |
| logs    | array  | The log of the JavaScript code     |
| result  | any    | The result of the JavaScript code  |
| message | string | The message of the JavaScript code |
| error   | string | The error of the JavaScript code   |

<details>

<summary>View JSON Schema</summary>

```json
{
  "description": "RunJavaScript node output.",
  "properties": {
    "logs": {
      "title": "Log",
      "type": "array",
      "description": "The log of the JavaScript code"
    },
    "result": {
      "title": "Result",
      "type": null,
      "description": "The result of the JavaScript code"
    },
    "message": {
      "title": "Message",
      "type": "string",
      "description": "The message of the JavaScript code"
    },
    "error": {
      "title": "Error",
      "type": "string",
      "description": "The error of the JavaScript code"
    }
  },
  "required": [
    "logs"
  ],
  "title": "RunJavaScriptNodeOutput",
  "type": "object"
}
```

</details>

## How It Works

This node executes your JavaScript code in a secure sandboxed environment. Your code must export an `execute` function that receives an object containing the node input, workflow run input, and workflow state. The function can use logging for debugging and must return a value that becomes the node's result. Any errors are caught and returned in the error field.

## Usage Examples

### Example 1: Simple Data Transformation

**Input:**

```
code: `
function execute(args) {
  const number = args.input.value;
  return number * 2;
}
`
input: {"value": 5}
```

**Output:**

```
logs: []
result: 10
message: "Execution completed successfully"
error: null
```

### Example 2: String Manipulation with Logging

**Input:**

```
code: `
function execute(args) {
  const text = args.input.text;
  log("Input text: " + text);
  const uppercase = text.toUpperCase();
  log("Converted to uppercase");
  return uppercase;
}
`
input: {"text": "hello world"}
```

**Output:**

```
logs: ["Input text: hello world", "Converted to uppercase"]
result: "HELLO WORLD"
message: "Execution completed successfully"
error: null
```

### Example 3: Complex Logic with Error Handling

**Input:**

```
code: `
function execute(args) {
  try {
    const items = args.input.items;
    log("Processing " + items.length + " items");

    const processed = items.map(item => ({
      ...item,
      processed_at: new Date().toISOString()
    }));

    return processed;
  } catch (e) {
    return { error: e.message };
  }
}
`
input: {"items": [{"id": 1, "name": "Item 1"}]}
```

**Output:**

```
logs: ["Processing 1 items"]
result: [{"id": 1, "name": "Item 1", "processed_at": "2024-01-15T10:30:00Z"}]
message: "Execution completed successfully"
error: null
```

## Common Use Cases

* **Data Transformation**: Convert data formats, calculations, and mappings
* **String Manipulation**: Parse, format, and transform text data
* **Array Operations**: Filter, map, reduce, and manipulate arrays
* **Conditional Logic**: Complex branching based on input data
* **Date/Time Processing**: Calculate dates, format timestamps, and handle time zones
* **Custom Calculations**: Perform mathematical or business logic calculations
* **Data Validation**: Validate input data against custom rules

## Error Handling

| Error Type               | Cause                                    | Solution                                                              |
| ------------------------ | ---------------------------------------- | --------------------------------------------------------------------- |
| Missing Execute Function | Code doesn't define an execute function  | Ensure your code exports an execute function                          |
| Syntax Error             | JavaScript syntax is invalid             | Check for missing brackets, semicolons, or typos                      |
| Runtime Error            | Error occurs during code execution       | Check error message and add try-catch blocks for risky operations     |
| Timeout                  | Code execution takes too long            | Optimize loops and remove inefficient operations                      |
| Undefined Variable       | Reference to variable that doesn't exist | Verify variable names and use typeof checks before access             |
| Return Type Error        | Returned value can't be serialized       | Ensure returned values are JSON-serializable (no circular references) |

## Notes

* **Function Structure**: Your JavaScript code must always define an `execute` function. This function receives an object with `input`, `workflow_run_input`, and `workflow_run_state` properties.
* **Return Value**: The value returned from the `execute` function becomes the `result` in the output.
* **Logging**: Use the `log()` function to output debug information during execution. These logs will be captured in the `logs` output field.
* **Error Handling**: If your code throws an error, it will be caught and returned in the `error` field. Wrap risky operations in try-catch blocks.
* **Context Access**: You have access to the entire workflow state and input within your JavaScript code, allowing complex transformations based on workflow context.
* **Security**: Code runs in a sandboxed environment with limited access to system resources.
