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

# Browser

> Configure Stagehand on Browserbase or locally

export const V3Banner = () => null;

<V3Banner />

Stagehand supports two primary environments:

* **Browserbase** - Cloud-managed browser infrastructure optimized for production web automation at scale
* **Local** - Run browsers directly on your machine for development and debugging

## Browserbase Environment

Browserbase provides managed cloud browser infrastructure optimized for web automation at scale. It offers advanced features like stealth mode, proxy support, and persistent contexts.

<Card icon="cloud" title="Browserbase" href="https://docs.browserbase.com" description="Explore the features and benefits of using Browserbase for scalable web automation.">
  Discover the power of cloud-managed browser infrastructure with Browserbase.
</Card>

### Multi-Region Support

Stagehand API is available in multiple regions to optimize latency and support data residency requirements. The SDK automatically routes requests to the correct regional API endpoint based on your browser session's region.

| Region                  | API Endpoint                                                                               |
| ----------------------- | ------------------------------------------------------------------------------------------ |
| **us-west-2** (Default) | [https://api.stagehand.browserbase.com](https://api.stagehand.browserbase.com)             |
| **us-east-1**           | [https://api.use1.stagehand.browserbase.com](https://api.use1.stagehand.browserbase.com)   |
| **eu-central-1**        | [https://api.euc1.stagehand.browserbase.com](https://api.euc1.stagehand.browserbase.com)   |
| **ap-southeast-1**      | [https://api.apse1.stagehand.browserbase.com](https://api.apse1.stagehand.browserbase.com) |

Configure your browser session region in `browserbaseSessionCreateParams`:

```typescript theme={null}
import { Stagehand } from "@browserbasehq/stagehand";

const stagehand = new Stagehand({
  env: "BROWSERBASE",
  browserbaseSessionCreateParams: {
    region: "eu-central-1", // Browser runs in Frankfurt
  },
});

await stagehand.init();
```

<Warning>
  The API endpoint must match your browser session region. If there's a mismatch, you'll receive an error:
  `Session is in region 'X' but this API instance serves 'Y'. Please route your request to the X Stagehand API endpoint.`
</Warning>

### Disabling Stagehand API

If you want to use Stagehand purely as a local library without routing through the Stagehand API, you can disable API mode:

```typescript theme={null}
import { Stagehand } from "@browserbasehq/stagehand";

const stagehand = new Stagehand({
  env: "BROWSERBASE",
  disableAPI: true, // Disable Stagehand API - runs locally with Browserbase
});

await stagehand.init();
```

<Tip>
  Disabling the API is useful when you want to manage browser sessions directly while still using Stagehand's automation features locally.
</Tip>

### Environment Variables

Before getting started, set up the required environment variables:

<CodeGroup>
  ```bash .env theme={null}
  BROWSERBASE_API_KEY=your_api_key_here
  ```
</CodeGroup>

<Tip>
  Get your API key from the [Browserbase Dashboard](https://browserbase.com/overview)
</Tip>

### Using Stagehand with Browserbase

#### Basic Setup

The simplest way to get started is with default settings:

```typescript theme={null}
import { Stagehand } from "@browserbasehq/stagehand";

const stagehand = new Stagehand({
  env: "BROWSERBASE",
});

await stagehand.init();
```

#### Advanced Configuration

Configure browser settings, proxy support, and other session parameters:

```typescript theme={null}
import { Stagehand } from "@browserbasehq/stagehand";

const stagehand = new Stagehand({
  env: "BROWSERBASE",
  // Optional: API Key will be pulled directly from your environment
  apiKey: process.env.BROWSERBASE_API_KEY,
  browserbaseSessionCreateParams: {
    proxies: true,
    region: "us-west-2",
    browserSettings: {
      viewport: { width: 1920, height: 1080 },
      blockAds: true,
    },
  },
});

await stagehand.init();
console.log("Session ID:", stagehand.sessionId);
```

<Accordion title="Advanced Browserbase Configuration Example">
  ```typescript theme={null}
  const stagehand = new Stagehand({
    env: "BROWSERBASE",
    apiKey: process.env.BROWSERBASE_API_KEY,
    browserbaseSessionCreateParams: {
      proxies: true,
      region: "us-west-2",
      timeout: 3600, // 1 hour session timeout
      keepAlive: true, // Available on Startup plan
      browserSettings: {
        advancedStealth: false, // this is a Scale Plan feature - reach out to support@browserbase.com to enable
        blockAds: true,
        solveCaptchas: true,
        recordSession: false,
        viewport: {
          width: 1920,
          height: 1080,
        },
      },
      userMetadata: {
        userId: "automation-user-123",
        environment: "production",
      },
    },
  });
  ```
</Accordion>

### Alternative: Browserbase SDK

If you prefer to manage sessions directly, you can use the Browserbase SDK:

```typescript theme={null}
import { Browserbase } from "@browserbasehq/sdk";

const bb = new Browserbase({ 
  apiKey: process.env.BROWSERBASE_API_KEY! 
});

const session = await bb.sessions.create({
  // Add configuration options here
});
```

#### Connecting to an Existing Session

Connect to a previously created Browserbase session using its session ID:

```typescript theme={null}
import { Stagehand } from "@browserbasehq/stagehand";

const stagehand = new Stagehand({
  env: "BROWSERBASE",
  browserbaseSessionID: "existing-session-uuid-here",
});

await stagehand.init();
console.log("Resumed Session ID:", stagehand.sessionId);
```

## Local Environment

The local environment runs browsers directly on your machine, providing full control over browser instances and configurations. Ideal for development, debugging, and scenarios requiring custom browser setups.

### Environment Comparison

| Feature                     | Browserbase                   | Local                         |
| --------------------------- | ----------------------------- | ----------------------------- |
| **Scalability**             | High (cloud-managed)          | Limited (local resources)     |
| **Stealth Features**        | Advanced fingerprinting       | Basic stealth                 |
| **Proxy Support**           | Built-in residential proxies  | Manual configuration          |
| **Session Persistence**     | Cloud context storage         | File-based user data          |
| **Geographic Distribution** | Multi-region deployment       | Single machine                |
| **Debugging**               | Session recordings & logs     | Direct DevTools access        |
| **Setup Complexity**        | Environment variables only    | Browser installation required |
| **Cost**                    | Usage-based pricing           | Infrastructure & maintenance  |
| **Best For**                | Production, scale, compliance | Development, debugging        |

### Basic Local Setup

```typescript theme={null}
import { Stagehand } from "@browserbasehq/stagehand";

const stagehand = new Stagehand({
  env: "LOCAL"
});
  
await stagehand.init();
console.log("Session ID:", stagehand.sessionId);
```

### Advanced Local Configuration

Customize browser launch options for local development:

```typescript theme={null}
import { Stagehand } from "@browserbasehq/stagehand";

const stagehand = new Stagehand({
  env: "LOCAL",
  localBrowserLaunchOptions: {
    headless: false, // Show browser window
    devtools: true, // Open developer tools
    viewport: { width: 1280, height: 720 },
    executablePath: '/opt/google/chrome/chrome', // Custom Chrome path
    port: 9222, // Fixed CDP debugging port
    args: [
      '--no-sandbox',
      '--disable-setuid-sandbox',
      '--disable-web-security',
      '--allow-running-insecure-content',
    ],
    userDataDir: './chrome-user-data', // Persist browser data
    preserveUserDataDir: true, // Keep data after closing
    chromiumSandbox: false, // Disable sandbox (adds --no-sandbox)
    ignoreHTTPSErrors: true, // Ignore certificate errors
    locale: 'en-US', // Set browser language
    deviceScaleFactor: 1.0, // Display scaling
    proxy: {
      server: 'http://proxy.example.com:8080',
      username: 'user',
      password: 'pass'
    },
    downloadsPath: './downloads', // Download directory
    acceptDownloads: true, // Allow downloads
    connectTimeoutMs: 30000, // Connection timeout
  },
});

await stagehand.init();
```

## Advanced Configuration

### Keep Alive

The `keepAlive` option controls whether the browser remains running after `stagehand.close()` is called or when the parent process exits unexpectedly (e.g., crash, `SIGTERM`, `SIGINT`).

By default, Stagehand terminates the browser and cleans up all resources when it shuts down. Setting `keepAlive: true` keeps the browser running independently so you can reconnect to it later.

```typescript theme={null}
import { Stagehand } from "@browserbasehq/stagehand";

const stagehand = new Stagehand({
  env: "BROWSERBASE",
  keepAlive: true,
});

await stagehand.init();

// The browser session continues running after close()
await stagehand.close();

// Later, reconnect to the same session
const stagehand2 = new Stagehand({
  env: "BROWSERBASE",
  browserbaseSessionID: stagehand.browserbaseSessionID,
});
await stagehand2.init();
```

#### Behavior by Environment

| Behavior            | `keepAlive: true`                    | `keepAlive: false` (default)                         |
| ------------------- | ------------------------------------ | ---------------------------------------------------- |
| **Browserbase**     | Session stays active after `close()` | Session is terminated via API                        |
| **Local**           | Chrome process continues running     | Chrome process is killed and temp profile is removed |
| **On crash/signal** | Browser is left running              | Browser is automatically cleaned up                  |

#### Local Environment

When running locally with `keepAlive: true`, the Chrome process is detached from the Node.js event loop, allowing your script to exit while the browser stays open. This is useful for debugging or for handing off a browser session to another process.

```typescript theme={null}
const stagehand = new Stagehand({
  env: "LOCAL",
  keepAlive: true,
  localBrowserLaunchOptions: {
    headless: false,
  },
});

await stagehand.init();
const page = stagehand.context.pages()[0];
await page.goto("https://example.com");

// Browser window stays open after the script exits
await stagehand.close();
```

#### Browserbase Environment

On Browserbase, `keepAlive: true` keeps the cloud session active so you can reconnect later using `browserbaseSessionID`. This is useful for long-running workflows that span multiple script executions.

<Note>
  The top-level `keepAlive` option overrides `browserbaseSessionCreateParams.keepAlive` when both are provided.
</Note>

### Fixed CDP Debugging Port

Specify a fixed Chrome DevTools Protocol (CDP) debugging port instead of using a randomly assigned one.

```typescript theme={null}
import { Stagehand } from "@browserbasehq/stagehand";

const stagehand = new Stagehand({
  env: "LOCAL",
  localBrowserLaunchOptions: {
    port: 9222,
  },
});

await stagehand.init();
```

<Tip>
  If no `port` is specified, a random port will be assigned.
</Tip>

### DOM Settle Timeout

Configure how long Stagehand waits for the DOM to stabilize before taking actions.

```typescript theme={null}
const stagehand = new Stagehand({
  env: "BROWSERBASE",
  domSettleTimeout: 3000 // Wait up to 3 seconds for DOM to settle
});
```

#### What is DOM Settling?

DOM settling ensures that:

* **Animations complete** before interacting with elements
* **Lazy-loaded content** has time to appear
* **JavaScript updates** finish before actions are taken
* **Dynamic content** is fully rendered

#### When to Adjust

Increase `domSettleTimeout` for pages with:

* Heavy animations or transitions
* Lazy-loading or infinite scroll
* Dynamic JavaScript frameworks (React, Vue, Angular)
* Complex single-page applications

```typescript theme={null}
// For fast, static pages
const stagehand = new Stagehand({
  env: "BROWSERBASE",
  domSettleTimeout: 500 // Minimal wait
});

// For dynamic, animated pages
const stagehand = new Stagehand({
  env: "BROWSERBASE",
  domSettleTimeout: 5000 // Longer wait for stability
});
```

<Warning>
  Setting `domSettleTimeout` too low may cause actions to fail on elements that aren't ready. Setting it too high increases execution time unnecessarily.
</Warning>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Browserbase Authentication Errors">
    * Verify your `BROWSERBASE_API_KEY` is set correctly
    * Check that your API key has the necessary permissions
    * Ensure your Browserbase account has sufficient credits
  </Accordion>

  <Accordion title="Local Browser Launch Failures">
    * Install Chrome or Chromium on your system
    * Set the correct `executablePath` for your Chrome installation
    * Check that required dependencies are installed (Linux: `libnss3-dev libatk-bridge2.0-dev libgtk-3-dev libxss1 libasound2`)
  </Accordion>

  <Accordion title="Session Timeout Issues">
    * Increase session timeout in `browserbaseSessionCreateParams.timeout`
    * Use `keepAlive: true` for long-running sessions
    * Monitor session usage to avoid unexpected terminations
  </Accordion>
</AccordionGroup>
