Skip to main content
Stagehand owns the browser connection and exposes top-level lifecycle, metrics, and AI methods.

Quick start

create()

Create a Stagehand instance and connect it to a browser. Stagehand.create() is the only way to build one; there is no public constructor, and the returned instance is already initialized.
StagehandBrowser
required
A browser handle from browserbase.launch(), browserbase.connect(), localBrowser.launch(), or localBrowser.connect(). Each handle can back only one Stagehand instance.
Promise<Stagehand>
An initialized Stagehand instance.

Properties

Read-only accessors on an instance.
StagehandBrowser
The browser handle you passed to Stagehand.create(). Reach pages and the context through it when you hold the instance but not the handle: stagehand.browser.context. Stagehand does not close this browser for you.
boolean
Whether the instance is connected and able to serve calls. This is false after close().

close()

Close the Stagehand session and release browser resources.
Promise<void>
Resolves after the operation completes.

experimentalBatch()

Run a trusted, self-contained JavaScript callback inside the Stagehand extension service worker. Operations made through the supplied batch context route directly through the worker, avoiding an SDK-to-browser round trip for every command.
Batch callbacks execute in the Stagehand service worker, not the webpage. Treat callback source as application code rather than untrusted input.

Callback arguments

Stagehand invokes the function in the service worker with two arguments: a worker-local ExperimentalBatchContext and the JSON input supplied to experimentalBatch().
The function parameter names are chosen by the caller. Destructuring is ordinary JavaScript shorthand, not special Stagehand injection syntax:
Callbacks may ignore arguments they do not need. For example, await stagehand.experimentalBatch(async () => "done") is valid.
ExperimentalBatchCallback<Input, Result>
A self-contained callback executed in the extension service worker. It receives the batch context first and input second. Values from the caller’s lexical scope are not captured.
Input
JSON-serializable input passed as the callback’s second argument. When omitted, the callback receives undefined; pass null explicitly to receive null.
ExperimentalBatchOptions
Options controlling the selected page and overall deadline.
Page
The page exposed as the callback context’s page. The active page at batch startup is used when omitted. This does not change the default target of act(), observe(), or extract(); those methods use their own page option or the active page when called.
number
The overall callback deadline in milliseconds. Defaults to 30,000.
Promise<Awaited<Result>>
The callback’s JSON-serializable return value.

Batch callback context

The callback receives an ExperimentalBatchContext, not the outer SDK Stagehand instance:
  • page: the worker-local Page selected when the batch starts;
  • context: a worker-local browser context facade;
  • act, observe, and extract: the normal Stagehand AI operations;
  • metrics: the normal Stagehand metrics operation.
The context intentionally does not expose context.close(), Stagehand lifecycle methods, nested callback batches, or page event subscriptions. Host-only behavior such as local file paths and screenshot output paths is also unavailable because the callback runs in a browser service worker, not Node.js.

Passing data across the worker boundary

The callback is serialized and evaluated in a different JavaScript runtime, so it cannot capture variables from the calling process. Pass external data through input, similarly to page.evaluate():
Both input and the callback’s return value must be JSON-serializable.

Selecting and targeting pages

options.page transfers an SDK page ID to the worker. The callback receives the corresponding worker-local page as batch.page; the outer Page object itself does not cross the boundary.
batch.page is fixed when the batch starts: it represents options.page, or the active page at startup when no page is supplied. The AI methods follow the same targeting rules as the regular SDK: an operation-level page option wins; otherwise they resolve the active page when the operation runs. Changing the active page therefore affects later act(), observe(), and extract() calls, but does not replace batch.page.
Timeout cancellation prevents the callback from starting further Stagehand operations. An operation already running when the timeout occurs may still finish, so a batch is not an atomic transaction.

metrics()

Return token usage and inference timing metrics for this session. Each Stagehand instance starts at zero. Every successful operation returns metadata.usage; deterministic actions and cache hits report zero-valued usage, so they leave the counters unchanged. Calls that throw before returning a result are not recorded. Reading metrics does not reset them.
Promise<StagehandMetrics>
The operation result.
number
Prompt tokens used.
number
Completion tokens used.
number
Reasoning tokens used.
number
Cached input tokens used.
number
Inference time in milliseconds.
number
Prompt tokens used.
number
Completion tokens used.
number
Reasoning tokens used.
number
Cached input tokens used.
number
Inference time in milliseconds.
number
Prompt tokens used.
number
Completion tokens used.
number
Reasoning tokens used.
number
Cached input tokens used.
number
Inference time in milliseconds.
number
Prompt tokens used.
number
Completion tokens used.
number
Reasoning tokens used.
number
Cached input tokens used.
number
Inference time in milliseconds.

act()

Perform an action described in natural language.
Action | string
A natural-language action to perform, or an action returned by observe().
string
The CSS selector or XPath for the action target.
string
A human-readable description of the action.
string
The action method to execute.
string[]
Arguments to pass to the action method.
StagehandClientActOptions
Options that configure this operation.
Caching
Override server-side caching with a boolean or threshold options object.
number
The positive identical-result threshold required before serving a cache hit.
Locator[]
Page-created locators to exclude from instruction-planning context. Create each with page.locator("..."); use .nth(index) on a locator to exclude only that indexed match.
Locator
The page locator that identifies the action target. Create it with page.locator("..."); use .nth(index) on the locator to target a specific match.
ModelConfig
Model configuration for this call. When neither this nor an initialized model exists, Browserbase selects one automatically for Gateway sessions.
string
The model provider API key.
object
Additional model provider headers.
ModelName
A supported provider-prefixed model identifier.
number
The operation timeout in milliseconds.
Variables
Variables available to the instruction.
Promise<ActResult>
The operation result.
ActResultData
The action outcome.
string
A summary of the completed action.
Action[]
The actions that were performed.
string[]
Arguments passed to the action.
string
A human-readable action description.
string
The action method.
string
The action target selector.
string
The operation message.
boolean
Whether the action succeeded.
StagehandResultMetadata
Metadata associated with the operation.
CacheMetadata
Cache observability for this result; status is DISABLED when no cache lookup ran.
CacheStatus
"HIT" when a cached result was served, "MISS" when the result was computed, or "DISABLED" when no cache lookup ran.
number
Times this cache key has been seen, including this request.
number
The hit-count threshold in effect for this key.
string
Why the cache did not serve this request; misses only.
CacheTokenSavings
LLM tokens avoided by serving this request from cache; hits only.
number
Input tokens avoided.
number
Output tokens avoided.
number
Total tokens avoided.
string
The action ID associated with the operation.
StagehandResultUsage
Aggregate LLM usage for the operation. All counters are 0 when the operation does not run inference.
number
Input tokens consumed by all LLM calls.
number
Output tokens consumed by all LLM calls.
number
Reasoning tokens consumed by all LLM calls.
number
Cached input tokens used by all LLM calls.
number
Total time spent waiting for LLM inference, in milliseconds.

observe()

Find candidate actions on the page from an optional instruction.
string
The natural-language instruction.
StagehandClientObserveOptions
Options that configure this operation.
Caching
Override server-side caching for this request. Requests with locator or ignoreLocators bypass server-side caching and return metadata.cache.status as DISABLED.
number
The identical-result threshold required before serving a cache hit.
Locator[]
Page-created CSS or XPath locators to exclude from consideration. Create each with page.locator("..."); use .nth(index) on a locator to exclude only that indexed match. text= locators are not yet supported for observe snapshot scoping.
Locator
A page-created CSS or XPath locator that scopes the operation. Create it with page.locator("..."); use .nth(index) on the locator to target a specific match. text= locators are not yet supported for observe snapshot scoping.
ModelConfig
Model configuration for this call. When neither this nor an initialized model exists, Browserbase selects one automatically for Gateway sessions.
string
The model provider API key.
object
Additional model provider headers.
ModelName
The model identifier.
number
The operation timeout in milliseconds.
Variables
Variables available to the instruction.
Promise<ObserveResult>
The operation result.
Action[]
Candidate actions found on the page.
string[]
Arguments passed to the action.
string
A human-readable action description.
string
The action method.
string
The action target selector.
StagehandResultMetadata
Metadata associated with the operation.
CacheMetadata
Cache observability for this result; status is DISABLED when no cache lookup ran.
CacheStatus
Whether server-side caching served or computed this result.
number
Times this cache key has been seen, including this request.
number
The hit-count threshold in effect for this key.
string
Why the cache did not serve this request; misses only.
CacheTokenSavings
LLM tokens avoided by serving this request from cache; hits only.
number
Input tokens avoided.
number
Output tokens avoided.
number
Total tokens avoided.
string
The action ID associated with the operation.
StagehandResultUsage
Aggregate LLM usage for the operation. All counters are 0 when the operation does not run inference.
number
Input tokens consumed by all LLM calls.
number
Output tokens consumed by all LLM calls.
number
Reasoning tokens consumed by all LLM calls.
number
Cached input tokens used by all LLM calls.
number
Total time spent waiting for LLM inference, in milliseconds.

extract()

Extract structured data from the page.
string
The natural-language instruction.
Schema
The schema used to validate extracted data. Defaults to an object with a string extraction field when omitted; when selecting a custom schema generic, provide the matching runtime schema.
StagehandClientExtractOptions
Options that configure this operation.
Caching
Override server-side caching for this request.
number
The identical-result threshold required before serving a cache hit.
Locator[]
Page-created CSS or XPath locators to exclude from consideration. Create each with page.locator("..."); use .nth(index) on a locator to exclude only that indexed match. text= locators are not yet supported for extract snapshot scoping.
Locator
A page-created CSS or XPath locator that scopes the operation. Create it with page.locator("..."); use .nth(index) on the locator to target a specific match. text= locators are not yet supported for extract snapshot scoping.
ModelConfig
Model configuration for this call. When neither this nor an initialized model exists, Browserbase selects one automatically for Gateway sessions.
string
The model provider API key.
object
Additional model provider headers.
ModelName
The model identifier.
boolean
Whether the operation may use a screenshot.
number
The operation timeout in milliseconds.
Promise<ExtractResult<Schema>>
The extraction result.
z.output<Schema>
Data validated against the caller’s schema.
StagehandResultMetadata
Metadata associated with the extraction.
CacheMetadata
Cache observability for this result; status is DISABLED when no cache lookup ran.
CacheStatus
Whether server-side caching served or computed this result.
number
Times this cache key has been seen, including this request.
number
The hit-count threshold in effect for this key.
string
Why the cache did not serve this request; misses only.
CacheTokenSavings
LLM tokens avoided by serving this request from cache; hits only.
number
Input tokens avoided.
number
Output tokens avoided.
number
Total tokens avoided.
string
The action ID associated with the extraction.
StagehandResultUsage
Aggregate LLM usage for the operation. All counters are 0 when the operation does not run inference.
number
Input tokens consumed by all LLM calls.
number
Output tokens consumed by all LLM calls.
number
Reasoning tokens consumed by all LLM calls.
number
Cached input tokens used by all LLM calls.
number
Total time spent waiting for LLM inference, in milliseconds.