# Execute Javascript Code (`rixin/execute-javascript-code`) Actor

Execute JavaScript code securely. Pay only for the seconds you use, starting from $1/hour. Supports multiple code blocks, custom timeouts, and detailed output capture (stdout/stderr). Fast, secure, and cost-effective for dynamic code execution tasks.

- **URL**: https://apify.com/rixin/execute-javascript-code.md
- **Developed by:** [Rixin Sc](https://apify.com/rixin) (community)
- **Categories:** Developer tools, Automation, Integrations
- **Stats:** 121 total users, 26 monthly users, 97.9% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.01 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

### What does Execute Javascript Code do?

Execute Javascript Code allows you to run arbitrary JavaScript code blocks securely in the cloud using the high-performance Bun runtime. It provides a flexible and cost-effective way to execute dynamic logic, perform calculations, or run one-off scripts without managing infrastructure.

- **Execute arbitrary JavaScript**: Run valid JavaScript code immediately.
- **High Performance**: Powered by the Bun runtime for fast startup and execution.
- **Secure Isolation**: Each execution runs in a restricted environment where the main actor script deletes itself to prevent introspection.
- **Pay-Per-Second**: You are charged only for the exact execution time (minimum 1 second), making it extremely affordable (~$1.00/hour).
- **Detailed Output**: Capture `stdout`, `stderr`, exit codes, and precise execution timing.
- **Flexible Input**: Support for single code snippets or batched code blocks with individual timeouts.

### What data can you get?

This Actor returns detailed information about the execution of your code blocks.

| | | |
| --- | --- | --- |
| 🆔 Code Block ID | 📤 Stdout | ⚠️ Stderr |
| 🚪 Exit Code | ⏱️ Execution Time | 💲 Charged Seconds |
| ❌ Error Details | 📅 Timestamp | |

### How to use Execute Javascript Code?

It's easy to get started with executing JavaScript code in the cloud.

1. [Create](https://console.apify.com/sign-up) a free Apify account.
2. Open **Execute Javascript Code**.
3. Enter the JavaScript code you want to run in the input field.
4. Click "Start" and wait for the execution to complete.
5. Download your results in JSON, CSV, or other formats.

### Input

The input is a JSON object where you can specify the code to execute. You can provide a single code string or a list of code blocks with custom configurations.

- **code**: A single string of JavaScript code to execute.
- **codeBlocks**: An array of objects, each containing `code` and optional `id` and `timeout`.
- **timeout**: Global default timeout in seconds (default: 60s, max: 7200s).

#### Input Example (Single Block)

```json
{
    "code": "console.log('Hello from Apify!');"
}
```

#### Input Example (Multiple Blocks)

```json
{
    "codeBlocks": [
        {
            "id": "calculation",
            "code": "console.log(Math.PI * Math.pow(5, 2));",
            "timeout": 5
        },
        {
            "id": "async-operation",
            "code": "await new Promise(r => setTimeout(r, 1000)); console.log('Done');",
            "timeout": 10
        }
    ],
    "timeout": 30
}
```

### Output

The results are stored in the default dataset. Each item represents the execution result of one code block.

#### Output Example

```json
{
    "codeBlockId": "calculation",
    "stdout": "78.53981633974483\n",
    "stderr": "",
    "exitCode": 0,
    "executionTimeSeconds": 0.015,
    "chargedSeconds": 1,
    "error": null,
    "executedAt": "2023-10-27T10:00:00.000Z"
}
```

### Integrations

You can integrate Execute Javascript Code with almost any cloud service or web app.

- **Make & Zapier**: Trigger code execution from other workflows.
- **Slack & Discord**: Send notifications based on execution results.
- **Google Sheets**: Process data from sheets using custom JS logic.
- **Webhooks**: Receive immediate notifications when your code finishes running.

### FAQ

#### How much does it cost?

This Actor uses the **Pay-Per-Event (PPE)** pricing model.

- **Price**: $0.000278 per second of execution time (approx. $1.00 per hour). Check latest pricing from the pricing tab.
- **Minimum**: 1 second per block.
  You pay only for what you use.

#### Can I use Execute Javascript Code with the Apify API?

Yes. The Apify API gives you programmatic access to the Apify platform. You can manage, schedule, and run Actors, access datasets, monitor performance, and more.
To access the API using Node.js, use the `apify-client` NPM package. To access the API using Python, use the `apify-client` PyPI package.

#### Can I use this Actor through an MCP Server?

Yes. You can use this Actor in conjunction with an MCP server to enable AI assistants to execute code.

1. Set up the Apify MCP server.
2. Allow the tool `actor-run` or similar.
3. The AI model can then invoke this Actor to run calculations or logic and get the results back.

#### Your feedback

We’re always working on improving the performance of our Actors. If you have any technical feedback or found a bug, please create an issue in the Issues tab.

# Actor input Schema

## `code` (type: `string`):

JavaScript code to execute. Use this or 'codeBlocks'.

## `codeBlocks` (type: `array`):

List of code blocks to execute sequentially. Each item should have a 'code' property and optional 'timeout' (in seconds).

## `timeout` (type: `integer`):

Default timeout in seconds for execution (max 7200).

## Actor input object example

```json
{
  "codeBlocks": [
    {
      "id": "example-1",
      "code": "console.log('Hello from Block 1');",
      "timeout": 5
    }
  ],
  "timeout": 60
}
```

# Actor output Schema

## `dataset` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "codeBlocks": [
        {
            "id": "example-1",
            "code": "console.log('Hello from Block 1');",
            "timeout": 5
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("rixin/execute-javascript-code").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "codeBlocks": [{
            "id": "example-1",
            "code": "console.log('Hello from Block 1');",
            "timeout": 5,
        }] }

# Run the Actor and wait for it to finish
run = client.actor("rixin/execute-javascript-code").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "codeBlocks": [
    {
      "id": "example-1",
      "code": "console.log('\''Hello from Block 1'\'');",
      "timeout": 5
    }
  ]
}' |
apify call rixin/execute-javascript-code --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,rixin/execute-javascript-code"
        }
    }
}

```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/yhaOeQsvrr2anKJuC/builds/lM5Y1NOordZPn4dDR/openapi.json
