Skip to main content

Getting Started

The fastest way to start using Stagehand

Overview

The Stagehand class is the main entry point for Stagehand v3. It manages browser lifecycle, provides AI-powered automation methods, and handles both local and remote browser environments.

Constructor

new Stagehand()

Create a new Stagehand instance.
V3Options Interface:

Configuration Parameters

env
"LOCAL" | "BROWSERBASE"
required
Environment to run the browser in.
  • "LOCAL" - Run browser locally using Chrome/Chromium
  • "BROWSERBASE" - Run browser on Browserbase cloud platform

Browserbase Options

apiKey
string
Browserbase API key. Required when env is "BROWSERBASE".Can also be set via BROWSERBASE_API_KEY environment variable.
browserbaseSessionID
string
Resume an existing Browserbase session by ID instead of creating a new one.
browserbaseSessionCreateParams
object
Additional parameters for Browserbase session creation. See Browserbase documentation for details.

Local Browser Options

localBrowserLaunchOptions
LocalBrowserLaunchOptions
Configuration for local Chrome/Chromium browser.

AI/LLM Configuration

model
ModelConfiguration
Configure the AI model to use for automation. Can be either:
  • A string in the format "provider/model" (e.g., "openai/gpt-4o", "anthropic/claude-sonnet-4-6")
  • An object with detailed configuration
llmClient
LLMClient
Provide a custom LLM client implementation instead of using the default.
systemPrompt
string
Custom system prompt to guide AI behavior across all operations.

Behavior Options

selfHeal
boolean
Enable self-healing mode where actions can recover from failures.Default: true
experimental
boolean
Enable experimental features (may change between versions).Default: false
Use with caution in production. Experimental features may break or change between versions without notice.
domSettleTimeout
number
Default timeout for waiting for DOM to stabilize (in milliseconds).Default: 30000
cacheDir
string
Directory path for caching action observations to improve performance.
keepAlive
boolean
Controls whether the browser remains running after stagehand.close() is called or the parent process exits unexpectedly.
  • true - Browser continues running independently. On Browserbase, the session stays active. Locally, the Chrome process is kept alive.
  • false - Browser is terminated and resources are cleaned up on close or crash.
When set, this overrides any value in browserbaseSessionCreateParams.keepAlive.Default: false
serverCache
boolean
Enable or disable server-side caching for act(), extract(), and observe() requests. When enabled, repeated calls with the same inputs return instantly without consuming LLM tokens.
Only applies when env is "BROWSERBASE". Has no effect in local environments.
Can be overridden per-call via the serverCache option on act(), extract(), and observe().Default: true

Logging Options

verbose
0 | 1 | 2
Logging verbosity level.
  • 0 - Minimal logging
  • 1 - Standard logging (default)
  • 2 - Detailed debug logging
Default: 1
logInferenceToFile
boolean
Log AI inference details to files for debugging.Default: false
disablePino
boolean
Disable the Pino logging backend (useful for custom logging integrations).Default: false
logger
(line: LogLine) => void
Custom logger function to receive log events.

Methods

init()

Initialize the Stagehand instance and launch the browser.
Must be called before using any other methods.

close()

Close the browser and clean up resources.
force
boolean
Force close even if already closing.Default: false
When keepAlive is true, calling close() disconnects Stagehand from the browser without terminating it. The browser session continues running independently and can be reconnected to later using browserbaseSessionID. When keepAlive is false (the default), close() fully terminates the browser and cleans up all resources.

agent()

Create an AI agent instance for autonomous multi-step workflows.
See the agent() reference for detailed documentation.

Properties

page

Access pages for browser automation. Pages are accessed through the context.
Type: Page The page object provides methods for:
  • Navigation (goto(), reload(), goBack(), goForward())
  • Interaction (click(), type(), keyPress(), locator(), deepLocator())
  • Inspection (url(), title(), screenshot())
  • JavaScript evaluation (evaluate())
Important: AI-powered methods (act(), extract(), observe()) are called on the stagehand instance, not on the page object.

context

Access the browser context for managing multiple pages.
Type: V3Context The context object provides:
  • newPage() - Create a new page/tab
  • pages() - Get all open pages
  • setActivePage(page) - Switch active page

metrics

Get usage metrics for AI operations.
Returns: Promise<StagehandMetrics> StagehandMetrics Interface:

history

Get the history of all operations performed.
Returns: Promise<ReadonlyArray<HistoryEntry>> HistoryEntry Interface:

browserbaseSessionID

Browserbase session identifier for the active Browserbase run.
Type: string | undefined — undefined for LOCAL runs or before init().

browserbaseSessionURL

Shareable link to the active Browserbase session dashboard.
Type: string | undefined — undefined until a Browserbase session is active.

browserbaseDebugURL

Debugger URL returned by Browserbase for direct CDP inspection.
Type: string | undefined — undefined for LOCAL runs or if Browserbase doesn’t provide one.

Code Examples

Error Handling

Stagehand methods may throw the following errors:
  • StagehandInitError - Failed to initialize Stagehand
  • StagehandNotInitializedError - Methods called before init()
  • BrowserbaseSessionNotFoundError - Browserbase session not found
  • MissingLLMConfigurationError - No LLM API key or client configured
  • MissingEnvironmentVariableError - Required environment variable not set
  • StagehandEnvironmentError - Invalid environment configuration
Always handle errors appropriately:

Best Practices

  1. Always call init() before using any other methods
  2. Always call close() when done to clean up resources
  3. Use try-finally to ensure cleanup even on errors
  4. Set appropriate timeouts based on your use case
  5. Enable selfHeal for more robust automation
  6. Use metrics to monitor token usage and costs
  7. Configure custom logger for production debugging
  8. Cache directory can significantly improve performance for repeated actions

Environment Variables

Stagehand recognizes the following environment variables:
  • BROWSERBASE_API_KEY - Browserbase API key
  • OPENAI_API_KEY - OpenAI API key
  • ANTHROPIC_API_KEY - Anthropic API key
  • GOOGLE_API_KEY - Google AI API key
These can be overridden by passing values in the constructor options.