> ## Documentation Index
> Fetch the complete documentation index at: https://docs.anchorbrowser.io/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Anchor Browser is cloud browser infrastructure for AI agents and automation: browser sessions you control over CDP or REST, natural-language web tasks, versioned automation tasks, managed authentication into third-party web apps (identities with MFA), persistent volumes and profiles, recordings, live view, batch sessions, webhooks, and network options including residential proxies, extra stealth, and captcha solving for sites that block standard browsers. The for-agents page (https://docs.anchorbrowser.io/for-agents) covers authentication and the first API calls. API keys are created at https://app.anchorbrowser.io/api-keys. Append .md to any page URL for its Markdown version. The SDKs read the API key from ANCHORBROWSER_API_KEY, and REST calls send it in the anchor-api-key header. End every session you create with DELETE /v1/sessions/{id}, because a session is billed until it ends. Location targeting, captcha solving and managed authentication need the Starter plan, and extra stealth needs the Growth plan; on the Free plan, create a session with an empty body. Plans and limits are at https://docs.anchorbrowser.io/pricing. The hosted MCP server is https://api.anchorbrowser.io/v1/mcp.

# Modal

> Run agent code in a Modal Sandbox and drive an Anchor cloud browser from it, with the sandbox locked to Anchor's hosts.

[Modal Sandboxes](https://modal.com/docs/guide/sandboxes) are secure containers for running code you did not write yourself, such as code an LLM generated. This guide runs that code in a Modal Sandbox and gives it a real browser on Anchor.

Every sample is in Python and TypeScript. Tested with the Modal Python SDK 1.7.0 and Anchor Python SDK 1.0.1, and with the Modal JavaScript SDK 0.12.0 and Anchor TypeScript SDK 1.0.0.

## What you're integrating

**Anchor SDK in a Modal image → Anchor Cloud.** The Sandbox stays small. Chromium runs as a managed Anchor cloud session; the Sandbox holds the SDK and talks to it over HTTPS and CDP.

* Modal stays the code runtime: install packages, run a script, call a model.
* Anchor stays the remote browser: stealth, proxies, live view and session lifecycle.
* Do not launch a browser inside the Sandbox.

Modal's own [computer use example](https://modal.com/docs/examples/computer_use_vnc) takes the other route: it installs Chromium, a virtual display and a VNC server in the Sandbox image and tunnels the desktop out. That works for local, unprotected pages. With Anchor there is nothing to install or tunnel, the image builds in seconds, the browser gets past bot detection, and you watch it through Anchor's live view instead of VNC.

## Before you start

Install Modal and log in. `modal setup` writes a token that both the Python and JavaScript SDKs read.

```bash Python theme={null}
pip install modal
python3 -m modal setup
```

```bash TypeScript theme={null}
pip install modal
python3 -m modal setup
npm install modal tsx
```

Create an Anchor key at [API Keys](https://app.anchorbrowser.io/api-keys) and store it as a Modal Secret, so it never sits in your code:

```bash theme={null}
modal secret create anchorbrowser ANCHORBROWSER_API_KEY=YOUR_ANCHOR_API_KEY
```

```text theme={null}
Created a new secret 'anchorbrowser' with the key 'ANCHORBROWSER_API_KEY'
```

Keep the name `ANCHORBROWSER_API_KEY`. The Python SDK reads it on its own, and the TypeScript samples pass it to the SDK.

## Build the image once

Modal recommends a named image for Sandboxes, so a Sandbox never waits on an image build when it starts. Build and publish one that holds the Anchor SDK and the Playwright client:

```python build_image.py theme={null}
import modal

app = modal.App.lookup("anchor-browser", create_if_missing=True)

image = modal.Image.debian_slim(python_version="3.12").pip_install(
    "anchorbrowser>=1.0",
    "playwright",
)

with modal.enable_output():
    image.build(app=app).publish("anchor-sandbox")

print("published image: anchor-sandbox")
```

```typescript build_image.ts theme={null}
import { ModalClient } from "modal";

const modal = new ModalClient();
const app = await modal.apps.fromName("anchor-browser", { createIfMissing: true });

const image = modal.images.fromRegistry("node:22-slim").dockerfileCommands([
  "WORKDIR /app",
  "RUN npm init -y && npm install anchorbrowser playwright-core",
]);

const built = await image.build(app);
await built.publish("anchor-sandbox-node");
console.log("published image: anchor-sandbox-node");
```

```bash Python theme={null}
python build_image.py
```

```bash TypeScript theme={null}
npx tsx build_image.ts
```

The Python build prints:

```text theme={null}
Successfully installed anchorbrowser-1.0.1 ... playwright ...
Built image im-... in 6.80s
published image: anchor-sandbox
```

The TypeScript samples use top-level `await`, so set `"type": "module"` in your `package.json`.

The same build in Modal's **Logs** tab:

![Modal logs showing the Anchor SDK and Playwright client installing and the image built in 6.80 seconds](https://mintcdn.com/anchor-b3ec2715/GLzJqFH4f_tCkX0s/images/integrations/modal/image-build-logs.png?fit=max\&auto=format\&n=GLzJqFH4f_tCkX0s\&q=85\&s=2b53eedef6788df332837c744d13b150)

`playwright` (Python) and `playwright-core` (Node.js) are only the client library that speaks CDP. You do not run `playwright install`, because the browser lives on Anchor. That is why the build takes seconds.

## Run a web task from the Sandbox

Describe the goal in plain English and let Anchor's agent drive the browser. The script below starts a Sandbox from the named image, attaches the Secret, runs the task and terminates the Sandbox.

```python run_task.py theme={null}
import modal

TASK = '''
import os
from anchorbrowser import Anchorbrowser

client = Anchorbrowser(api_key=os.environ["ANCHORBROWSER_API_KEY"])
result = client.agent.task(
    "Go to books.toscrape.com and return the title and price of the first three books"
)
print(result.data.result)

# The task started its own browser session. End it so it stops billing.
client.sessions.delete_session(result.data.sessionId)
print("anchor session ended")
'''

app = modal.App.lookup("anchor-browser", create_if_missing=True)

sb = modal.Sandbox.create(
    app=app,
    image=modal.Image.from_name("anchor-sandbox"),
    secrets=[modal.Secret.from_name("anchorbrowser")],
    timeout=10 * 60,
)

try:
    p = sb.exec("python", "-c", TASK, timeout=5 * 60)
    print(p.stdout.read())
    err = p.stderr.read()
    if err:
        print("stderr:", err)
    p.wait()
    print("exit code:", p.returncode)
finally:
    sb.terminate()
```

```typescript run_task.ts theme={null}
import { ModalClient } from "modal";

const TASK = `
import { client, agentTask, Sessions } from "anchorbrowser";

client.setConfig({ auth: () => process.env.ANCHORBROWSER_API_KEY });

const result = await agentTask(
  "Go to books.toscrape.com and return the title and price of the first three books"
);
console.log(result.data.result);

// The task started its own browser session. End it so it stops billing.
await Sessions.deleteSession({ path: { session_id: result.sessionId } });
console.log("anchor session ended");
`;

const modal = new ModalClient();
const app = await modal.apps.fromName("anchor-browser", { createIfMissing: true });
const image = await modal.images.fromName("anchor-sandbox-node");
const secret = await modal.secrets.fromName("anchorbrowser");

const sb = await modal.sandboxes.create(app, image, {
  secrets: [secret],
  workdir: "/app",
  timeoutMs: 10 * 60 * 1000,
});

try {
  const p = await sb.exec(["node", "--input-type=module", "-e", TASK], {
    timeoutMs: 5 * 60 * 1000,
  });
  console.log(await p.stdout.readText());
  const err = await p.stderr.readText();
  if (err) console.log("stderr:", err);
  console.log("exit code:", await p.wait());
} finally {
  await sb.terminate();
}
```

```bash Python theme={null}
python run_task.py
```

```bash TypeScript theme={null}
npx tsx run_task.ts
```

Both print:

```text theme={null}
1. A Light in the Attic — £51.77
2. Tipping the Velvet — £53.74
3. Soumission — £50.10
anchor session ended

exit code: 0
```

You run these with plain `python` or `tsx`, not `modal run`. A Sandbox created from outside Modal only needs an App to belong to, which `modal.App.lookup` and `modal.apps.fromName` provide.

In the TypeScript version the Sandbox starts in `/app`, the directory where the image installed the packages, so `node` can resolve `anchorbrowser`.

Each run shows up under the App's **Sandboxes** tab in Modal:

![Modal Sandboxes page for the anchor-browser app showing seven Sandboxes created, with lifetime, CPU and memory charts](https://mintcdn.com/anchor-b3ec2715/GLzJqFH4f_tCkX0s/images/integrations/modal/sandboxes-metrics.png?fit=max\&auto=format\&n=GLzJqFH4f_tCkX0s\&q=85\&s=8214f13b2a86a3074a42a771a74f45c2)

> [!NOTE]
>
> A web task starts a browser session and leaves it running when the task finishes. End it as the scripts do, with `delete_session(result.data.sessionId)` in Python or `Sessions.deleteSession` in TypeScript, or it stays open until Anchor's idle timeout.

## Drive the browser yourself with Playwright

For step-by-step control, create an Anchor session and connect Playwright to it over CDP from inside the Sandbox.

```python run_playwright.py theme={null}
import modal

SCRIPT = '''
import os
from anchorbrowser import Anchorbrowser
from playwright.sync_api import sync_playwright

client = Anchorbrowser(api_key=os.environ["ANCHORBROWSER_API_KEY"])
session = client.sessions.create_session(
    session={"timeout": {"max_duration": 10, "idle_timeout": 3}}
)
print("live view:", session.data.live_view_url)

try:
    with sync_playwright() as p:
        browser = p.chromium.connect_over_cdp(session.data.cdp_url)
        context = browser.contexts[0]
        page = context.pages[0] if context.pages else context.new_page()
        page.goto("https://books.toscrape.com")
        print("title:", page.title())
        print("first book:", page.get_attribute("article.product_pod h3 a", "title"))
        browser.close()
finally:
    client.sessions.delete_session(session.data.id)
    print("anchor session ended")
'''

app = modal.App.lookup("anchor-browser", create_if_missing=True)

sb = modal.Sandbox.create(
    app=app,
    image=modal.Image.from_name("anchor-sandbox"),
    secrets=[modal.Secret.from_name("anchorbrowser")],
    timeout=10 * 60,
)

try:
    p = sb.exec("python", "-c", SCRIPT, timeout=5 * 60)
    print(p.stdout.read())
    err = p.stderr.read()
    if err:
        print("stderr:", err)
    p.wait()
    print("exit code:", p.returncode)
finally:
    sb.terminate()
```

```typescript run_playwright.ts theme={null}
import { ModalClient } from "modal";

const SCRIPT = `
import { client, Sessions } from "anchorbrowser";
import { chromium } from "playwright-core";

client.setConfig({ auth: () => process.env.ANCHORBROWSER_API_KEY });

const session = await Sessions.createSession({
  body: { session: { timeout: { max_duration: 10, idle_timeout: 3 } } },
});
console.log("live view:", session.data.live_view_url);

try {
  const browser = await chromium.connectOverCDP(session.data.cdp_url);
  const context = browser.contexts()[0];
  const page = context.pages()[0] ?? (await context.newPage());
  await page.goto("https://books.toscrape.com");
  console.log("title:", await page.title());
  console.log(
    "first book:",
    await page.getAttribute("article.product_pod h3 a", "title")
  );
  await browser.close();
} finally {
  await Sessions.deleteSession({ path: { session_id: session.data.id } });
  console.log("anchor session ended");
}
`;

const modal = new ModalClient();
const app = await modal.apps.fromName("anchor-browser", { createIfMissing: true });
const image = await modal.images.fromName("anchor-sandbox-node");
const secret = await modal.secrets.fromName("anchorbrowser");

const sb = await modal.sandboxes.create(app, image, {
  secrets: [secret],
  workdir: "/app",
  timeoutMs: 10 * 60 * 1000,
});

try {
  const p = await sb.exec(["node", "--input-type=module", "-e", SCRIPT], {
    timeoutMs: 5 * 60 * 1000,
  });
  console.log(await p.stdout.readText());
  const err = await p.stderr.readText();
  if (err) console.log("stderr:", err);
  console.log("exit code:", await p.wait());
} finally {
  await sb.terminate();
}
```

Both print:

```text theme={null}
live view: https://live.anchorbrowser.io/inspector.html?sessionId=<session-id>&rt=<token>
title: All products | Books to Scrape - Sandbox
first book: A Light in the Attic
anchor session ended

exit code: 0
```

> [!WARNING]
>
> `session.data.cdp_url` and `session.data.live_view_url` carry a session token (`rt`). Anyone who has one of them can reach that browser until the session ends. Do not write them to logs you share.

### Watch the browser

Open the `live view` URL in your own browser while the script runs, or open the session in the [Anchor dashboard](https://app.anchorbrowser.io). You see the live browser next to the session details and the task run:

![Anchor dashboard session page with the live browser on books.toscrape.com and a successful task run](https://mintcdn.com/anchor-b3ec2715/GLzJqFH4f_tCkX0s/images/integrations/modal/anchor-session.png?fit=max\&auto=format\&n=GLzJqFH4f_tCkX0s\&q=85\&s=d1a7d7a1a1dd2da2f1ad1543c9b6ed15)

This is the Anchor session streaming directly, so the Sandbox needs no tunnel, display or VNC server.

## Lock the Sandbox to Anchor

By default a Modal Sandbox can reach any public address. When the code inside is untrusted, limit it to the two hosts the Anchor SDK needs with a Modal [Outbound Policy](https://modal.com/docs/guide/sandbox-networking):

```python Python theme={null}
policy = modal.OutboundPolicy(
    routes=[
        modal.OutboundRoute.tls(
            domains=["api.anchorbrowser.io", "connect.anchorbrowser.io"]
        ),
        modal.OutboundRoute.any().block(),
    ],
)

sb = modal.Sandbox.create(
    app=app,
    image=modal.Image.from_name("anchor-sandbox"),
    secrets=[modal.Secret.from_name("anchorbrowser")],
    outbound_policy=policy,
    timeout=10 * 60,
)
```

```typescript TypeScript theme={null}
import { ModalClient, OutboundPolicy, OutboundRoute } from "modal";

const policy = new OutboundPolicy({
  routes: [
    OutboundRoute.tls({
      domains: ["api.anchorbrowser.io", "connect.anchorbrowser.io"],
    }),
    OutboundRoute.any().block(),
  ],
});

const sb = await modal.sandboxes.create(app, image, {
  secrets: [secret],
  workdir: "/app",
  outboundPolicy: policy,
  timeoutMs: 10 * 60 * 1000,
});
```

Running the Playwright script in that Sandbox, followed by a request to another site, prints:

```text Python theme={null}
title: All products | Books to Scrape - Sandbox
anchor session ended
example.org: blocked URLError
```

```text TypeScript theme={null}
title: All products | Books to Scrape - Sandbox
first book: A Light in the Attic
anchor session ended
example.org: blocked ENOTFOUND
```

The code can still browse any site, because the page loads happen in Anchor's browser, not in the Sandbox. It just cannot open its own connections anywhere else. This is the main reason to pair the two: the agent's code is boxed in, and all web access goes through one browser you can watch and record.

| Host | Used for |
| - | - |
| `api.anchorbrowser.io` | Creating and ending sessions, running tasks |
| `connect.anchorbrowser.io` | The CDP websocket Playwright connects to |

`live.anchorbrowser.io` is opened by the person watching, not by the Sandbox, so it does not need to be on the list.

## Clean up two lifecycles

There are two things to end, and ending one does not end the other.

* **The Anchor session.** End it in a `finally` block. Terminating the Sandbox stops the Sandbox only; the cloud browser keeps running and billing until its own timeout.
* **The Modal Sandbox.** Call `sb.terminate()` in a `finally` block. A Sandbox lives for 5 minutes by default; pass `timeout` (seconds, Python) or `timeoutMs` (milliseconds, TypeScript) when you create it for up to 24 hours.
* Set Anchor's `timeout.max_duration` and `timeout.idle_timeout`, in minutes, as a safety net for a Sandbox that dies mid-run. See [Session Timeout](https://docs.anchorbrowser.io/advanced/session-timeout.md).
* Reuse one Anchor session for a whole agent run instead of creating one per page.

To confirm nothing is left running:

```bash theme={null}
curl https://api.anchorbrowser.io/v1/sessions/all/status \
  -H "anchor-api-key: $ANCHORBROWSER_API_KEY"
```

## API key

Each customer brings their own Anchor key as a Modal Secret named `anchorbrowser`. Anchor bills them directly for browser usage; Modal bills for the Sandbox.

## Troubleshooting

* **`401` from Anchor inside the Sandbox:** the Secret is missing or the variable has a different name. Run `modal secret list` and check the Secret holds `ANCHORBROWSER_API_KEY`.
* **The Sandbox waits a long time to start:** it is building the image inline. Build and publish the named image first, then load it by name.
* **`getaddrinfo ENOTFOUND connect.anchorbrowser.io` after adding an Outbound Policy:** only `api.anchorbrowser.io` is on the list. The session is created, but Playwright cannot open the CDP websocket. Add `connect.anchorbrowser.io`.
* **`ERR_REQUIRE_ASYNC_MODULE` when running a `.ts` script:** the project is not an ES module. Set `"type": "module"` in `package.json`.
* **The Sandbox exits before the task finishes:** raise the timeout on the Sandbox and on `sb.exec`. A web task can take a few minutes.

See the [Sandboxes overview](https://docs.anchorbrowser.io/integrations/sandboxes) and [Create a Session](https://docs.anchorbrowser.io/quickstart/create-session.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.