TSEP · Source conservée

Stagehand — Browser configuration

Vue texte dérivée de la capture ; le document original reste la preuve.

Affirmations et preuves · Télécharger l’original gzip · Source de l’éditeur

Origine et méthode

SHA-256
0faa227011cc5395a55a770dad02127f998c99304709d072377a5f66ec9d1afd
Capture
Collecte
anonymous_http_response_body
Vue texte
Extraction du texte du DOM ; scripts, styles et contenus intégrés omis

L’empreinte des octets décompressés a été vérifiée avant cet affichage. Le texte est échappé ; aucun script ni ressource du document source n’est exécuté. La présentation, les images et l’ordre de lecture peuvent différer de l’original.

Texte de la source éditrice : Stagehand — Browser configuration. Reproduit pour vérification ; les droits et licences d’origine restent applicables. Demande de retrait : agence@edikka.com.

Passage référencé

Browser → introduction; browserbase.launch, localBrowser.launch, localBrowser.connect

AIA-stagehand-environments

Le localisateur n’a pas été résolu automatiquement en un extrait précis. Retrouvez ce repère dans la vue texte ci-dessous ou dans l’original ; cette ancre ne certifie pas à elle seule le passage.

Texte de la capture

Documentation Index

Fetch the complete documentation index at: /llms.txt

Use this file to discover all available pages before exploring further.

Skip to main content

Assistant

Responses are generated using AI and may contain mistakes.

Stagehand home page

Search...

⌘K

Discord

GitHub

Changelog

First steps

Introduction

Quickstart

Installation

AI rules

The basics

Act

Extract

Observe

WebMCP

Configuration

Browser

Logging

Add-ons

Search

Fetch

Models

Observability

Integrations

Overview

Agent Frameworks

CLI Agents

Applications

Best practices

Prompting best practices

Observe use cases

Caching actions

Using multiple tabs

User data

Speed optimization

Cost optimization

Deploying Stagehand

Cookbooks

Overview

Reuse an authenticated session

Export a paginated book catalog

Save extracted files to a bucket

Approve a form submission

Build an AI SDK research agent

Migration guide

Migrate v3 to v4

Migrate Playwright to v4

SDK reference

Stagehand

context

clipboard

page

WebMCP

response

locator

Discord

Support

v4

Stagehand home page
v4

Search...

⌘KAsk Assistant⌘I

Discord

Support

Search...

Navigation

Configuration

Browser

Configuration

Browser

Copy pageCopy page

Configure Stagehand on Browserbase or locally

Copy pageCopy page

You get a browser from one of Stagehand’s browser factories and hand it to Stagehand.create(). There are three ways to get one:

Browserbase (browserbase.launch): Cloud-managed browser infrastructure optimized for production web automation at scale

Local (localBrowser.launch): Run browsers directly on your machine for development and debugging

Attach over CDP (localBrowser.connect): Attach to any Chromium browser you are already running, by URL

Stagehand closes only the browsers it launched, so browser.close() is yours to call.

TypeScript

Python

Go

const cloud = await browserbase.launch({ apiKey: process.env.BROWSERBASE_API_KEY });
const local = await localBrowser.launch({ headless: true });
const connected = await localBrowser.connect({ cdpUrl: "http://127.0.0.1:9222" });

await Stagehand.create({ browser: cloud });

cloud = await browserbase.launch(api_key=os.environ["BROWSERBASE_API_KEY"])
local = await local_browser.launch(headless=True)
connected = await local_browser.connect(cdp_url="http://127.0.0.1:9222")

await Stagehand.create(browser=cloud)

apiKey := os.Getenv("BROWSERBASE_API_KEY")

cloud, _ := stagehand.LaunchBrowserbase(ctx, stagehand.BrowserbaseLaunchOptions{APIKey: apiKey})
stagehand.Create(ctx, stagehand.CreateOptions{Browser: cloud})

// Or start a browser on your machine, or attach to one you already run:
stagehand.LaunchLocalBrowser(ctx, &stagehand.LocalBrowserLaunchOptions{Headless: true})
stagehand.ConnectLocalBrowser(ctx, stagehand.LocalBrowserConnectOptions{
CDPURL: "http://127.0.0.1:9222",
})

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. It is also the only browser that supports server-side caching and the Model Gateway.

Browserbase

Read the Browserbase documentation for the full set of session settings Stagehand passes through.

Multi-region support

Browserbase runs browsers in four regions, so you can cut latency by starting the browser near your users or your target site, and keep session data in a required jurisdiction. Set the region on browserbase.launch(); us-west-2 is the default.

TypeScript

Python

Go

import { browserbase, Stagehand } from "@browserbasehq/stagehand";

const browser = await browserbase.launch({
apiKey: process.env.BROWSERBASE_API_KEY,
region: "eu-central-1", // Browser runs in Frankfurt
});
const stagehand = await Stagehand.create({ browser });

import os

from stagehand import Stagehand, browserbase

browser = await browserbase.launch(
api_key=os.environ["BROWSERBASE_API_KEY"],
region="eu-central-1", # Browser runs in Frankfurt
)
stagehand = await Stagehand.create(browser=browser)

apiKey := os.Getenv("BROWSERBASE_API_KEY")
region := stagehand.BrowserbaseRegionEUCentral1 // Browser runs in Frankfurt

browser, err := stagehand.LaunchBrowserbase(ctx, stagehand.BrowserbaseLaunchOptions{
APIKey: apiKey,
Region: &region,
})
if err != nil {
return err
}

client, err := stagehand.Create(ctx, stagehand.CreateOptions{
Browser: browser,
})
if err != nil {
return err
}
defer func() { err = errors.Join(err, client.Close(ctx)) }()

Supported regions: us-west-2 (default), us-east-1, eu-central-1, ap-southeast-1.

You normally do not need to configure a regional endpoint. Stagehand picks the API deployment that matches your session’s region on its own, including for server-side caching. An explicit Stagehand apiUrl overrides that regional selection.

API endpoint overrides

Browserbase session management and Stagehand managed services use separate APIs. Both default to the production service. The SDKs do not read either URL from an environment variable. Pass baseUrl to Browserbase and apiUrl to Stagehand when testing another deployment. Use the service origin without /v1.

TypeScript

Python

Go

const browser = await browserbase.launch({
apiKey: process.env.BROWSERBASE_API_KEY,
baseUrl: "https://api.dev.browserbase.com",
});

const stagehand = await Stagehand.create({
browser,
apiUrl: "https://api.stagehand.dev.browserbase.com",
});

browser = await browserbase.launch(
api_key=os.environ["BROWSERBASE_API_KEY"],
base_url="https://api.dev.browserbase.com",
)

stagehand = await Stagehand.create(
browser=browser,
api_url="https://api.stagehand.dev.browserbase.com",
)

apiKey := os.Getenv("BROWSERBASE_API_KEY")
stagehandAPIURL := "https://api.stagehand.dev.browserbase.com"

browser, err := stagehand.LaunchBrowserbase(ctx, stagehand.BrowserbaseLaunchOptions{
APIKey: apiKey,
BaseURL: "https://api.dev.browserbase.com",
})
if err != nil {
return err
}

client, err := stagehand.Create(ctx, stagehand.CreateOptions{
Browser: browser,
APIURL: &stagehandAPIURL,
})
if err != nil {
return err
}
defer func() { err = errors.Join(err, client.Close(ctx)) }()

The Browserbase URL controls extension, session, and connection requests that browserbase.launch() and browserbase.connect() make. The Stagehand URL controls Model Gateway and managed-cache requests that the browser runtime makes.

Browserbase client options

browserbase.launch() and browserbase.connect() create a Browserbase client for session and extension requests. Pass clientOptions (TypeScript), client_options (Python), or ClientOptions (Go) to tune that client’s timeout, retries, default headers, and default query parameters. TypeScript also accepts a custom fetch, Python accepts an httpx.AsyncClient as http_client, and Go accepts an *http.Client as HTTPClient. apiKey and baseUrl stay top-level, so one key authenticates both Browserbase and Stagehand.

TypeScript

Python

Go

const browser = await browserbase.launch({
apiKey: process.env.BROWSERBASE_API_KEY,
clientOptions: {
timeout: 30_000, // milliseconds
maxRetries: 1,
defaultHeaders: { "X-Request-Source": "my-app" },
},
});

browser = await browserbase.launch(
api_key=os.environ["BROWSERBASE_API_KEY"],
client_options={
"timeout": 30.0, # seconds
"max_retries": 1,
"default_headers": {"X-Request-Source": "my-app"},
},
)

maxRetries := 1
browser, err := stagehand.LaunchBrowserbase(ctx, stagehand.BrowserbaseLaunchOptions{
APIKey: os.Getenv("BROWSERBASE_API_KEY"),
ClientOptions: &stagehand.BrowserbaseClientOptions{
Timeout: 30 * time.Second, // per attempt
MaxRetries: &maxRetries,
DefaultHeaders: map[string]string{"X-Request-Source": "my-app"},
// HTTPClient: myHTTPClient, // optional caller-owned *http.Client
},
})
if err != nil {
return err
}

Units follow each SDK: TypeScript timeouts are in milliseconds, Python timeouts are in seconds, and Go uses a time.Duration that bounds each attempt. Stagehand never closes an http_client you pass; keep it open until browser.close() returns, because releasing the session uses it. Go never modifies an HTTPClient you pass, so its own Timeout and Transport still apply. In every SDK, default headers override the client’s own headers on conflict, including X-BB-API-Key and User-Agent. Go rejects invalid header names or values before sending any request.

Environment variables

Before getting started, set up the required environment variables:

export BROWSERBASE_API_KEY=your_api_key_here

Get your API key from the Browserbase Dashboard. Stagehand does not read this variable for you: read it in your own code and pass it to browserbase.launch().

Using Stagehand with Browserbase

Basic setup

The simplest way to get started is with default settings. browserbase.launch() needs nothing but your Browserbase API key:

TypeScript

Python

Go

import { browserbase, Stagehand } from "@browserbasehq/stagehand";

const browser = await browserbase.launch({
apiKey: process.env.BROWSERBASE_API_KEY,
});
const stagehand = await Stagehand.create({ browser });

import os

from stagehand import Stagehand, browserbase

browser = await browserbase.launch(
api_key=os.environ["BROWSERBASE_API_KEY"],
)
stagehand = await Stagehand.create(browser=browser)

apiKey := os.Getenv("BROWSERBASE_API_KEY")

browser, err := stagehand.LaunchBrowserbase(ctx, stagehand.BrowserbaseLaunchOptions{APIKey: apiKey})
if err != nil {
return err
}

client, err := stagehand.Create(ctx, stagehand.CreateOptions{
Browser: browser,
})
if err != nil {
return err
}
defer func() { err = errors.Join(err, client.Close(ctx)) }()

Advanced configuration

Configure browser settings, proxy support, and other session parameters directly on browserbase.launch():

TypeScript

Python

Go

import { browserbase, Stagehand } from "@browserbasehq/stagehand";

const browser = await browserbase.launch({
apiKey: process.env.BROWSERBASE_API_KEY,
proxies: true,
region: "us-west-2",
browserSettings: {
viewport: { width: 1920, height: 1080 },
blockAds: true,
},
});
const stagehand = await Stagehand.create({ browser });

import os

from stagehand import BrowserbaseBrowserSettings, Stagehand, browserbase

browser = await browserbase.launch(
api_key=os.environ["BROWSERBASE_API_KEY"],
proxies=True,
region="us-west-2",
browser_settings=BrowserbaseBrowserSettings.model_validate({
"viewport": {"width": 1920, "height": 1080},
"block_ads": True,
}),
)
stagehand = await Stagehand.create(browser=browser)

apiKey := os.Getenv("BROWSERBASE_API_KEY")
region := stagehand.BrowserbaseRegionUSWest2
proxies := stagehand.BrowserbaseProxyEnabled(true)
blockAds := true
width, height := 1920.0, 1080.0

browser, err := stagehand.LaunchBrowserbase(ctx, stagehand.BrowserbaseLaunchOptions{
APIKey: apiKey,
Proxies: &proxies,
Region: &region,
BrowserSettings: &stagehand.BrowserbaseBrowserSettings{
Viewport: &stagehand.BrowserbaseViewport{Width: &width, Height: &height},
BlockAds: &blockAds,
},
})
if err != nil {
return err
}

client, err := stagehand.Create(ctx, stagehand.CreateOptions{
Browser: browser,
})
if err != nil {
return err
}
defer func() { err = errors.Join(err, client.Close(ctx)) }()

Advanced Browserbase configuration example

TypeScript

Python

Go

const browser = await browserbase.launch({
apiKey: process.env.BROWSERBASE_API_KEY,
proxies: true,
region: "us-west-2",
timeout: 3600, // 1 hour session timeout
keepAlive: true, // Available on Startup plan
browserSettings: {
verified: 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",
},
});

browser = await browserbase.launch(
api_key=os.environ["BROWSERBASE_API_KEY"],
proxies=True,
region="us-west-2",
timeout=3600, # 1 hour session timeout
keep_alive=True, # Available on Startup plan
browser_settings=BrowserbaseBrowserSettings.model_validate({
# verified is a Scale Plan feature: contact support@browserbase.com to enable
"verified": False,
"block_ads": True,
"solve_captchas": True,
"record_session": False,
"viewport": {"width": 1920, "height": 1080},
}),
user_metadata={
"user_id": "automation-user-123",
"environment": "production",
},
)

stagehand = await Stagehand.create(browser=browser)

apiKey := os.Getenv("BROWSERBASE_API_KEY")
region := stagehand.BrowserbaseRegionUSWest2
proxies := stagehand.BrowserbaseProxyEnabled(true)
timeout := 3600.0 // 1 hour session timeout
keepAlive := true // Available on Startup plan

// verified is a Scale Plan feature: contact support@browserbase.com to enable
verified := false
blockAds := true
solveCaptchas := true
recordSession := false
width, height := 1920.0, 1080.0

browser, err := stagehand.LaunchBrowserbase(ctx, stagehand.BrowserbaseLaunchOptions{
APIKey: apiKey,
Proxies: &proxies,
Region: &region,
Timeout: &timeout,
KeepAlive: &keepAlive,
BrowserSettings: &stagehand.BrowserbaseBrowserSettings{
Verified: &verified,
BlockAds: &blockAds,
SolveCaptchas: &solveCaptchas,
RecordSession: &recordSession,
Viewport: &stagehand.BrowserbaseViewport{Width: &width, Height: &height},
},
UserMetadata: map[string]json.RawMessage{
"userId": json.RawMessage(`"automation-user-123"`),
"environment": json.RawMessage(`"production"`),
},
})
if err != nil {
return err
}

client, err := stagehand.Create(ctx, stagehand.CreateOptions{
Browser: browser,
})
if err != nil {
return err
}

defer func() { err = errors.Join(err, client.Close(ctx)) }()

When browserbase.launch() creates a session without an extensionId, Stagehand uploads its extension and starts the session against it. Stagehand deletes the upload when you call browser.close() for a launched session.

Alternative: Browserbase SDK

If you prefer to manage sessions directly, export the Stagehand extension and upload it to Browserbase first and include that uploaded extension when you create the session. Extensions cannot be added after a browser session starts. You can then hand Stagehand the resulting session through browserbase.connect():

The extension ID used to create the session is the uploaded-extension resource ID returned by the Browserbase Extensions API. browserbase.launch() handles this upload and session configuration automatically.

TypeScript

Python

Go

import { Browserbase } from "@browserbasehq/sdk";
import { browserbase, Stagehand } from "@browserbasehq/stagehand";

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

const session = await bb.sessions.create({
projectId: process.env.BROWSERBASE_PROJECT_ID!,
extensionId: process.env.BROWSERBASE_STAGEHAND_EXTENSION_ID!,
// Add configuration options here
});

// Attach by session ID so the browser keeps its Browserbase identity
const browser = await browserbase.connect({
apiKey: process.env.BROWSERBASE_API_KEY!,
sessionId: session.id,
});
const stagehand = await Stagehand.create({ browser });

import os

from browserbase import Browserbase

from stagehand import Stagehand
from stagehand import browserbase as stagehand_browserbase

bb = Browserbase(api_key=os.environ["BROWSERBASE_API_KEY"])

session = bb.sessions.create(
project_id=os.environ["BROWSERBASE_PROJECT_ID"],
extension_id=os.environ["BROWSERBASE_STAGEHAND_EXTENSION_ID"],
# Add configuration options here
)

# Attach by session ID so the browser keeps its Browserbase identity
browser = await stagehand_browserbase.connect(
api_key=os.environ["BROWSERBASE_API_KEY"],
session_id=session.id,
)
stagehand = await Stagehand.create(browser=browser)

// Create the session with your Browserbase client of choice, including the
// uploaded Stagehand extension, then attach by session ID.
extensionID := os.Getenv("BROWSERBASE_STAGEHAND_EXTENSION_ID")
session, err := createBrowserbaseSession(ctx, extensionID)
if err != nil {
return err
}

browser, err := stagehand.ConnectBrowserbase(ctx, stagehand.BrowserbaseConnectOptions{
APIKey: os.Getenv("BROWSERBASE_API_KEY"),
SessionID: session.ID,
})
if err != nil {
return err
}

client, err := stagehand.Create(ctx, stagehand.CreateOptions{
Browser: browser,
})
if err != nil {
return err
}
defer func() { err = errors.Join(err, client.Close(ctx)) }()

Connecting over CDP

localBrowser.connect() attaches to a running Chromium browser through its DevTools endpoint. It discovers an installed Stagehand extension first, then loads the bundled extension if none is found or discovery is unsupported. Loading requires a shared filesystem. For Browserbase sessions, use browserbase.connect() with the session ID; the extension must already be installed.

Connect-time extensionId / extension_id / ExtensionID is deprecated and ignored.

TypeScript

Python

Go

import { localBrowser, Stagehand } from "@browserbasehq/stagehand";

const browser = await localBrowser.connect({
cdpUrl: "http://127.0.0.1:9222",
});
const stagehand = await Stagehand.create({ browser });

from stagehand import Stagehand, local_browser

browser = await local_browser.connect(
cdp_url="http://127.0.0.1:9222",
)
stagehand = await Stagehand.create(browser=browser)

browser, err := stagehand.ConnectLocalBrowser(ctx, stagehand.LocalBrowserConnectOptions{
CDPURL: "http://127.0.0.1:9222",
})
if err != nil {
return err
}
defer func() { err = errors.Join(err, browser.Close(ctx)) }()

client, err := stagehand.Create(ctx, stagehand.CreateOptions{Browser: browser})
if err != nil {
return err
}
defer func() { err = errors.Join(err, client.Close(ctx)) }()

Connecting with authentication headers

If the browser service you connect to requires authentication headers, pass them using headers (TypeScript and Python) or Headers (Go). This lets you authenticate without putting credentials in the connection URL.

TypeScript

Python

Go

const browser = await localBrowser.connect({
cdpUrl: "https://gateway.example/cdp",
headers: { "X-Api-Key": process.env.CDP_GATEWAY_API_KEY! },
});

import os

browser = await local_browser.connect(
cdp_url="https://gateway.example/cdp",
headers={"X-Api-Key": os.environ["CDP_GATEWAY_API_KEY"]},
)

browser, err := stagehand.ConnectLocalBrowser(ctx, stagehand.LocalBrowserConnectOptions{
CDPURL: "https://gateway.example/cdp",
Headers: map[string]string{"X-Api-Key": os.Getenv("CDP_GATEWAY_API_KEY")},
})
if err != nil {
return err
}

Headers are sent with HTTP discovery and the client’s WebSocket connection. They are only forwarded to the same host and port, without switching from a secure connection to an insecure one.

Headers are never passed to the extension. Its connection must work without them, using a signed URL or a separate CDP URL.

A separate CDP URL for the extension

If the client connects through a proxy or authenticated gateway, you can give the extension a separate browser-level CDP WebSocket URL:

TypeScript

Python

Go

import { localBrowser, Stagehand } from "@browserbasehq/stagehand";

const browser = await localBrowser.connect({
cdpUrl: "wss://gateway.example/cdp?token=YOUR_GATEWAY_TOKEN",
extensionCdpUrl: "ws://127.0.0.1:9300/devtools/browser/BROWSER_ID",
});
const stagehand = await Stagehand.create({ browser });

from stagehand import Stagehand, local_browser

browser = await local_browser.connect(
cdp_url="wss://gateway.example/cdp?token=YOUR_GATEWAY_TOKEN",
extension_cdp_url="ws://127.0.0.1:9300/devtools/browser/BROWSER_ID",
)
stagehand = await Stagehand.create(browser=browser)

browser, err := stagehand.ConnectLocalBrowser(ctx, stagehand.LocalBrowserConnectOptions{
CDPURL: "wss://gateway.example/cdp?token=YOUR_GATEWAY_TOKEN",
ExtensionCDPURL: "ws://127.0.0.1:9300/devtools/browser/BROWSER_ID",
})
if err != nil {
return err
}
defer func() { err = errors.Join(err, browser.Close(ctx)) }()

client, err := stagehand.Create(ctx, stagehand.CreateOptions{Browser: browser})
if err != nil {
return err
}
defer func() { err = errors.Join(err, client.Close(ctx)) }()

The override must use ws:// or wss://, include a host, and use a port between 1 and 65535 if specified. Both endpoints must reach the same browser. When the option is omitted (None in Python or an empty string in Go), the extension uses the client’s resolved CDP WebSocket URL.
In this example, 127.0.0.1 refers to the browser’s environment. The extension can use any host reachable from inside Chrome. Using a separate endpoint keeps the gateway URL and its credentials out of the extension and avoids routing the extension’s CDP commands through the gateway.

Stagehand never closes a browser it did not launch. When you connect to an existing browser, close() tears down the Stagehand connection and leaves the browser running.

Local environment

Run browsers directly on your machine when you want full control over the browser process and its launch flags. This suits development, debugging, and custom browser setups.

Environment comparison

FeatureBrowserbaseLocal

ScalabilityHigh (cloud-managed)Limited (local resources)

Stealth featuresAdvanced fingerprintingBasic stealth

Proxy supportBuilt-in residential proxiesManual configuration

Session persistenceCloud context storageFile-based user data

Geographic distributionMulti-region deploymentSingle machine

DebuggingSession recordings and logsDirect DevTools access

Setup complexityAPI key onlyBrowser installation required

Server-side cachingSupportedNot available

Model GatewaySupportedNot available

CostUsage-based pricingInfrastructure and maintenance

Best forProduction, scale, complianceDevelopment, debugging

Basic local setup

TypeScript

Python

Go

import { localBrowser, Stagehand } from "@browserbasehq/stagehand";

const browser = await localBrowser.launch();
const stagehand = await Stagehand.create({ browser });

from stagehand import Stagehand, local_browser

browser = await local_browser.launch()
stagehand = await Stagehand.create(browser=browser)

browser, err := stagehand.LaunchLocalBrowser(ctx, &stagehand.LocalBrowserLaunchOptions{})
if err != nil {
return err
}

client, err := stagehand.Create(ctx, stagehand.CreateOptions{
Browser: browser,
})
if err != nil {
return err
}
defer func() { err = errors.Join(err, client.Close(ctx)) }()

Advanced local configuration

Customize browser launch options for local development:

TypeScript

Python

Go

import { localBrowser, Stagehand } from "@browserbasehq/stagehand";

const browser = await localBrowser.launch({
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
ignoreDefaultArgs: [
"--disable-sync",
], // Remove specific default launch args
args: [
"--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
hasTouch: false, // Emulate touch input
proxy: {
server: "http://proxy.example.com:8080",
username: "user",
password: "pass",
},
downloadsPath: "./downloads", // Download directory
acceptDownloads: true, // Allow downloads
});
const stagehand = await Stagehand.create({ browser });

from stagehand import Stagehand, local_browser

browser = await local_browser.launch(
headless=False, # Show browser window
devtools=True, # Open developer tools
viewport_width=1280,
viewport_height=720,
executable_path="/opt/google/chrome/chrome", # Custom Chrome path
port=9222, # Fixed CDP debugging port
ignore_default_args=["--disable-sync"], # Remove specific default launch args
args=[
"--disable-web-security",
"--allow-running-insecure-content",
],
user_data_dir="./chrome-user-data", # Persist browser data
preserve_user_data_dir=True, # Keep data after closing
chromium_sandbox=False, # Disable sandbox (adds --no-sandbox)
ignore_https_errors=True, # Ignore certificate errors
locale="en-US", # Set browser language
device_scale_factor=1.0, # Display scaling
has_touch=False, # Emulate touch input
proxy_server="http://proxy.example.com:8080",
proxy_username="user",
proxy_password="pass",
downloads_path="./downloads", # Download directory
accept_downloads=True, # Allow downloads
)
stagehand = await Stagehand.create(browser=browser)

chromiumSandbox := false // Disable sandbox (adds --no-sandbox)
acceptDownloads := true // Allow downloads
deviceScaleFactor := 1.0 // Display scaling

browser, err := stagehand.LaunchLocalBrowser(ctx, &stagehand.LocalBrowserLaunchOptions{
Headless: false, // Show browser window
Devtools: true, // Open developer tools
Viewport: &stagehand.LocalViewport{Width: 1280, Height: 720},
ExecutablePath: "/opt/google/chrome/chrome", // Custom Chrome path
Port: 9222, // Fixed CDP debugging port
IgnoreDefaultArgs: &stagehand.IgnoreDefaultArgs{ // Remove specific default launch args
Args: []string{"--disable-sync"},
},
Args: []string{
"--disable-web-security",
"--allow-running-insecure-content",
},
UserDataDir: "./chrome-user-data", // Persist browser data
PreserveUserDataDir: true, // Keep data after closing
ChromiumSandbox: &chromiumSandbox,
IgnoreHTTPSErrors: true, // Ignore certificate errors
Locale: "en-US", // Set browser language
DeviceScaleFactor: &deviceScaleFactor,
HasTouch: false, // Emulate touch input
Proxy: &stagehand.LocalProxyConfig{
Server: "http://proxy.example.com:8080",
Username: "user",
Password: "pass",
},
DownloadsPath: "./downloads", // Download directory
AcceptDownloads: &acceptDownloads,
})
if err != nil {
return err
}

client, err := stagehand.Create(ctx, stagehand.CreateOptions{
Browser: browser,
})
if err != nil {
return err
}
defer func() { err = errors.Join(err, client.Close(ctx)) }()

Authenticated local proxies are not supported yet. Setting a proxy username or password raises in all three SDKs; a proxy server and bypass list work everywhere.

Default local launch arguments

When Stagehand launches a local browser, it adds the following Chrome arguments before any values you pass in the launch args:

TypeScript

Python

Go

[
"--enable-unsafe-extension-debugging",
"--remote-allow-origins=*",
"--window-size=1280,800",
"--enable-features=WebMCP,WebMCPTesting,DevToolsWebMCPSupport",
]

[
"--enable-unsafe-extension-debugging",
"--remote-allow-origins=*",
"--window-size=1280,800",
"--enable-features=WebMCP,WebMCPTesting,DevToolsWebMCPSupport",
]

[]string{
"--enable-unsafe-extension-debugging",
"--remote-allow-origins=*",
"--window-size=1280,800",
"--enable-features=WebMCP,WebMCPTesting,DevToolsWebMCPSupport",
}

--enable-unsafe-extension-debugging is required so the SDK can attach a CDP session to the service worker hosting Stagehand’s runtime. Chrome blocks debugger access to extension targets without it. --enable-features=WebMCP,WebMCPTesting,DevToolsWebMCPSupport turns on the browser support behind WebMCP across supported Chrome versions. --window-size follows the viewport option and falls back to 1280,800 when you do not set one.

A larger set of standard Chrome automation flags (disabling background networking, component updates, sync, translation, and similar) is prepended as well. To remove some of them, list the exact flags in the ignore-default-args option:

TypeScript

Python

Go

const browser = await localBrowser.launch({
ignoreDefaultArgs: ["--disable-sync"],
args: [
"--disable-features=site-per-process,IsolateOrigins",
"--renderer-process-limit=6",
],
});

browser = await local_browser.launch(
ignore_default_args=["--disable-sync"],
args=[
"--disable-features=site-per-process,IsolateOrigins",
"--renderer-process-limit=6",
],
)

stagehand = await Stagehand.create(browser=browser)

browser, err := stagehand.LaunchLocalBrowser(ctx, &stagehand.LocalBrowserLaunchOptions{
IgnoreDefaultArgs: &stagehand.IgnoreDefaultArgs{
Args: []string{"--disable-sync"},
},
Args: []string{
"--disable-features=site-per-process,IsolateOrigins",
"--renderer-process-limit=6",
},
})
if err != nil {
return err
}

stagehand.Create(ctx, stagehand.CreateOptions{Browser: browser})

Set the ignore-default-args option to true to remove all default arguments. Use a list to remove only exact matches while preserving the rest.

Exporting the Stagehand extension

Each SDK exposes the extension bundled with its installed version as ZIP bytes. Use this archive to upload the extension to Browserbase or extract it for local installation in Chrome. These helpers do not require a Stagehand instance or a browser session and do not write files themselves.

TypeScript

Python

Go

getExtensionArchive() returns Promise<Uint8Array>.

import { writeFile } from "node:fs/promises";
import { getExtensionArchive } from "@browserbasehq/stagehand";

const archive = await getExtensionArchive();
await writeFile("stagehand-extension.zip", archive);

get_extension_archive() returns bytes synchronously.

from pathlib import Path
from stagehand import get_extension_archive

archive = get_extension_archive()
Path("stagehand-extension.zip").write_bytes(archive)

ExtensionArchive() returns an independent copy of the archive as []byte.

package main

import (
"log"
"os"

stagehand "github.com/browserbase/stagehand/packages/sdk-go/v4"
)

func main() {
archive := stagehand.ExtensionArchive()
if err := os.WriteFile("stagehand-extension.zip", archive, 0o644); err != nil {
log.Fatal(err)
}
}

Upload to Browserbase

Upload stagehand-extension.zip using the Browserbase Extensions API or the CLI deployment workflow. Include the returned extension ID when creating the session, as shown in Alternative: Browserbase SDK. browserbase.launch() handles the upload automatically when you omit an extension ID.

Load unpacked in Chrome

Extract stagehand-extension.zip to a folder.

Open chrome://extensions and enable Developer mode.

Click Load unpacked and select the extracted folder containing manifest.json.

The archive contains manifest.json at its root. Load unpacked requires the extracted files on disk; it cannot accept ZIP bytes or a ZIP file directly. Keep the extracted folder available while the extension is installed.
You can also extract the archive directly from Python:

import io
import zipfile
from stagehand import get_extension_archive

with zipfile.ZipFile(io.BytesIO(get_extension_archive())) as archive:
archive.extractall("stagehand-extension")

Select the stagehand-extension folder in Load unpacked. To attach Stagehand to that browser, it must also expose a DevTools endpoint; see Connecting over CDP.

Advanced configuration

Keep alive

Keep-alive keeps a launched browser running after stagehand.close() or after your script exits, so you can reconnect to it later. Call browser.close() when you’re done. It closes the browser even with keep-alive on.

Keeping sessions alive is available on the Browserbase Startup plan and above.

TypeScript

Python

Go

import { browserbase, Stagehand } from "@browserbasehq/stagehand";

const browser = await browserbase.launch({
apiKey: process.env.BROWSERBASE_API_KEY,
keepAlive: true,
});
const stagehand = await Stagehand.create({ browser });
const sessionId = browser.sessionId!;

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

// Later, reconnect to the same Browserbase session
const browser2 = await browserbase.connect({
apiKey: process.env.BROWSERBASE_API_KEY,
sessionId,
});
const stagehand2 = await Stagehand.create({ browser: browser2 });

// End the session when you're done
await stagehand2.close();
// This doesn't delete the extension that launch() uploaded.
// Pass extensionId to launch() to reuse one upload, or delete the upload separately.
await browser2.close();

import os

from stagehand import Stagehand, browserbase

browser = await browserbase.launch(
api_key=os.environ["BROWSERBASE_API_KEY"],
keep_alive=True,
)
stagehand = await Stagehand.create(browser=browser)
session_id = browser.session_id
assert session_id is not None

# The session keeps running after stagehand.close()
await stagehand.close()

# Later, reconnect to the same Browserbase session
browser2 = await browserbase.connect(
api_key=os.environ["BROWSERBASE_API_KEY"],
session_id=session_id,
)
stagehand2 = await Stagehand.create(browser=browser2)

# End the session when you're done
await stagehand2.close()
# This doesn't delete the extension that launch() uploaded.
# Pass extension_id to launch() to reuse one upload, or delete the upload separately.
await browser2.close()

apiKey := os.Getenv("BROWSERBASE_API_KEY")
keepAlive := true

browser, err := stagehand.LaunchBrowserbase(ctx, stagehand.BrowserbaseLaunchOptions{
APIKey: apiKey,
KeepAlive: &keepAlive,
})
if err != nil {
return err
}
client, err := stagehand.Create(ctx, stagehand.CreateOptions{Browser: browser})
if err != nil {
return err
}
sessionID := browser.SessionID()

// The session keeps running after client.Close()
if err := client.Close(ctx); err != nil {
return err
}

// Later, reconnect to the same Browserbase session
browser2, err := stagehand.ConnectBrowserbase(ctx, stagehand.BrowserbaseConnectOptions{
APIKey: apiKey,
SessionID: sessionID,
})
if err != nil {
return err
}

client2, err := stagehand.Create(ctx, stagehand.CreateOptions{
Browser: browser2,
})
if err != nil {
return err
}
// End the session when you're done. browser2.Close() doesn't delete the extension that
// LaunchBrowserbase uploaded. Pass ExtensionID to reuse one upload, or delete the upload separately.
defer func() { err = errors.Join(err, client2.Close(ctx), browser2.Close(ctx)) }()

Behavior by environment

EnvironmentAfter stagehand.close()After browser.close()

Browserbase, launch()Session keeps running until browser.close() or its timeoutEnds the session

Local, launch()Chrome keeps runningKills Chrome and removes the temp profile

Browserbase, connect()Session keeps runningEnds the session

Local, connect()Browser keeps runningCloses the browser

Local environment

When running locally with keep-alive on, Stagehand leaves the Chrome process running when your script exits. This is useful for debugging or for handing off a browser session to another process. Combine it with a fixed port so you can reattach with localBrowser.connect().

TypeScript

Python

Go

const browser = await localBrowser.launch({
keepAlive: true,
headless: false,
port: 9222,
});
const stagehand = await Stagehand.create({ browser });
const [page] = await browser.context.pages();
await page.goto("https://example.com");

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

browser = await local_browser.launch(
keep_alive=True,
headless=False,
port=9222,
)
stagehand = await Stagehand.create(browser=browser)
page = (await browser.context.pages())[0]
await page.goto("https://example.com")

# Browser window stays open after the script exits
await stagehand.close()

browser, err := stagehand.LaunchLocalBrowser(ctx, &stagehand.LocalBrowserLaunchOptions{
KeepAlive: true,
Headless: false,
Port: 9222,
})
if err != nil {
return err
}
client, err := stagehand.Create(ctx, stagehand.CreateOptions{Browser: browser})
if err != nil {
return err
}

browserContext, err := browser.Context()
if err != nil {
return err
}
pages, err := browserContext.Pages(ctx)
if err != nil {
return err
}
if len(pages) == 0 {
return errors.New("Stagehand initialized without an active page")
}
page := pages[0]
if _, err := page.Goto(ctx, "https://example.com", nil); err != nil {
return err
}

// Browser window stays open after the program exits
return client.Close(ctx)

A temporary user data directory is deleted when a local browser shuts down. Set userDataDir (or turn on the preserve option) if you want the profile to survive.

Fixed CDP debugging port

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

TypeScript

Python

Go

import { localBrowser, Stagehand } from "@browserbasehq/stagehand";

const browser = await localBrowser.launch({ port: 9222 });
const stagehand = await Stagehand.create({ browser });

from stagehand import Stagehand, local_browser

browser = await local_browser.launch(port=9222)
stagehand = await Stagehand.create(browser=browser)

browser, err := stagehand.LaunchLocalBrowser(ctx, &stagehand.LocalBrowserLaunchOptions{Port: 9222})
if err != nil {
return err
}

client, err := stagehand.Create(ctx, stagehand.CreateOptions{
Browser: browser,
})
if err != nil {
return err
}
defer func() { err = errors.Join(err, client.Close(ctx)) }()

Stagehand picks a random free port when you do not set one.

DOM settle timeout

Configure how long Stagehand waits for the DOM to stabilize before taking actions. The default is 5000 ms.

TypeScript

Python

Go

const browser = await browserbase.launch({ apiKey: process.env.BROWSERBASE_API_KEY });
const stagehand = await Stagehand.create({
browser,
domSettleTimeoutMs: 3000, // Wait up to 3 seconds for DOM to settle
});

browser = await browserbase.launch(api_key=os.environ["BROWSERBASE_API_KEY"])
stagehand = await Stagehand.create(
browser=browser,
dom_settle_timeout_ms=3000, # Wait up to 3 seconds for DOM to settle
)

apiKey := os.Getenv("BROWSERBASE_API_KEY")
domSettleTimeoutMs := 3000 // Wait up to 3 seconds for DOM to settle

browser, err := stagehand.LaunchBrowserbase(ctx, stagehand.BrowserbaseLaunchOptions{APIKey: apiKey})
if err != nil {
return err
}
client, err := stagehand.Create(ctx, stagehand.CreateOptions{
Browser: browser,
DOMSettleTimeoutMs: &domSettleTimeoutMs,
})
if err != nil {
return err
}

defer func() { err = errors.Join(err, client.Close(ctx)) }()

DOM settling applies to act() calls that take a natural-language instruction. Replaying an observed Action skips the wait, and observe() and extract() read a snapshot of the page as they find it.

What is DOM settling?

Before an instruction-based act() call runs, Stagehand waits for the page’s network activity to go quiet, up to the timeout. That gives lazy-loaded content, JavaScript updates, and other dynamic rendering time to finish before the action targets an element.

When to adjust

Increase the DOM settle timeout for pages with:

Heavy animations or transitions

Lazy-loading or infinite scroll

Dynamic JavaScript frameworks (React, Vue, Angular)

Complex single-page applications

TypeScript

Python

Go

// For fast, static pages
const fastBrowser = await browserbase.launch({ apiKey: process.env.BROWSERBASE_API_KEY });
const fast = await Stagehand.create({
browser: fastBrowser,
domSettleTimeoutMs: 500, // Minimal wait
});

// For dynamic, animated pages
const dynamicBrowser = await browserbase.launch({ apiKey: process.env.BROWSERBASE_API_KEY });
const dynamic = await Stagehand.create({
browser: dynamicBrowser,
domSettleTimeoutMs: 5000, // Longer wait for stability
});

# For fast, static pages
fast_browser = await browserbase.launch(api_key=os.environ["BROWSERBASE_API_KEY"])
fast = await Stagehand.create(
browser=fast_browser,
dom_settle_timeout_ms=500, # Minimal wait
)

# For dynamic, animated pages
dynamic_browser = await browserbase.launch(api_key=os.environ["BROWSERBASE_API_KEY"])
dynamic = await Stagehand.create(
browser=dynamic_browser,
dom_settle_timeout_ms=5000, # Longer wait for stability
)

apiKey := os.Getenv("BROWSERBASE_API_KEY")

browser, err := stagehand.LaunchBrowserbase(ctx, stagehand.BrowserbaseLaunchOptions{APIKey: apiKey})
if err != nil {
return err
}
settleTimeout := 500 // Fast, static pages
if os.Getenv("PAGE_PROFILE") == "dynamic" {
settleTimeout = 5000 // Dynamic, animated pages
}
client, err := stagehand.Create(ctx, stagehand.CreateOptions{
Browser: browser,
DOMSettleTimeoutMs: &settleTimeout,
})
if err != nil {
return err
}
defer func() { err = errors.Join(err, client.Close(ctx)) }()

Setting the DOM settle timeout too low may cause actions to fail on elements that aren’t ready. Setting it too high increases execution time unnecessarily.

Troubleshooting

Browserbase authentication errors

Verify your BROWSERBASE_API_KEY is read and passed to browserbase.launch()

Check that your API key has the necessary permissions

Ensure your Browserbase account has sufficient credits

Remember that browserbase.launch() requires an API key: it fails without one

Local browser launch failures

Install Chrome or Chromium on your system

Set the correct executable path for your Chrome installation, or set CHROME_PATH

Check that required dependencies are installed (Linux: libnss3-dev libatk-bridge2.0-dev libgtk-3-dev libxss1 libasound2)

If the extension fails to load, confirm nothing is stripping --enable-unsafe-extension-debugging from the launch arguments

Session timeout issues

Increase the session timeout on browserbase.launch()

Turn on keep-alive for long-running sessions

Monitor session usage to avoid unexpected terminations

Previous

Logging
Control terminal output and forward structured Stagehand logs

Next

⌘I

discordxgithublinkedin

Powered byThis documentation is built and hosted on Mintlify, a developer documentation platform

On this page
Back to top
Browserbase environment
Multi-region support

API endpoint overrides

Browserbase client options

Environment variables

Using Stagehand with Browserbase

Basic setup

Advanced configuration

Alternative: Browserbase SDK

Connecting over CDP

Connecting with authentication headers

A separate CDP URL for the extension

Local environment
Environment comparison

Basic local setup

Advanced local configuration

Default local launch arguments

Exporting the Stagehand extension
Upload to Browserbase

Load unpacked in Chrome

Advanced configuration
Keep alive

Behavior by environment

Local environment

Fixed CDP debugging port

DOM settle timeout

What is DOM settling?

When to adjust

Troubleshooting