Stagehand
Stagehand ↗ is an open-source, AI-powered browser automation library. Stagehand lets you combine code with natural-language instructions powered by AI, eliminating the need to dictate exact steps or specify selectors. With Stagehand, your agents are more resilient to website changes and easier to maintain, helping you build more reliably and flexibly.
This guide shows you how to deploy a Worker that uses Stagehand, Browser Rendering, and Workers AI to automate a web task.
In this example, you will use Stagehand to search for a movie on this example movie directory ↗, extract its details (title, year, rating, duration, and genre), and return the information along with a screenshot of the webpage.
See an example of the result
If instead you want to skip the steps and get started right away, select Deploy to Cloudflare below.
After you deploy, you can interact with the Worker using this URL pattern:
https://<your-worker>.workers.dev
Install the necessary dependencies:
npm ci
Update your wrangler configuration file to include the bindings for Browser Rendering and Workers AI:
{ "name": "stagehand-example", "main": "src/index.ts", "compatibility_flags": ["nodejs_compat"], "compatibility_date": "2025-09-17", "observability": { "enabled": true }, "browser": { "binding": "BROWSER" }, "ai": { "binding": "AI" } }
name = "stagehand-example"main = "src/index.ts"compatibility_flags = [ "nodejs_compat" ]compatibility_date = "2025-09-17"
[observability]enabled = true
[browser]binding = "BROWSER"
[ai]binding = "AI"
If you are using the Cloudflare Vite plugin ↗, you need to include the following alias ↗ in vite.config.ts
:
export default defineConfig({ // ... resolve: { alias: { 'playwright': '@cloudflare/playwright', }, },});
If you are not using the Cloudflare Vite plugin, you need to include the following module alias ↗ to the wrangler configuration:
{ // ... "alias": { "playwright": "@cloudflare/playwright" }}
Copy workersAIClient.ts ↗ to your project.
Then, in your Worker code, import the workersAIClient.ts
file and use it to configure a new Stagehand
instance:
import { Stagehand } from "@browserbasehq/stagehand";import { z } from "zod";import { endpointURLString } from "@cloudflare/playwright";import { WorkersAIClient } from "./workersAIClient";
export default { async fetch(request: Request, env: Env) { if (new URL(request.url).pathname !== "/") return new Response("Not found", { status: 404 });
const stagehand = new Stagehand({ env: "LOCAL", localBrowserLaunchOptions: { cdpUrl: endpointURLString(env.BROWSER) }, llmClient: new WorkersAIClient(env.AI), verbose: 1, });
await stagehand.init(); const page = stagehand.page;
await page.goto('https://demo.playwright.dev/movies');
// if search is a multi-step action, stagehand will return an array of actions it needs to act on const actions = await page.observe('Search for "Furiosa"'); for (const action of actions) await page.act(action);
await page.act('Click the search result');
// normal playwright functions work as expected await page.waitForSelector('.info-wrapper .cast');
let movieInfo = await page.extract({ instruction: 'Extract movie information', schema: z.object({ title: z.string(), year: z.number(), rating: z.number(), genres: z.array(z.string()), duration: z.number().describe("Duration in minutes"), }), });
await stagehand.close();
return Response.json(movieInfo); },};
npm run build
After you deploy, you can interact with the Worker using this URL pattern:
https://<your-worker>.workers.dev
npm run deploy
AI Gateway is a service that adds observability to your AI applications. By routing your requests through AI Gateway, you can monitor and debug your AI applications.
To use AI Gateway with a third-party model, first create a gateway in the Cloudflare dashboard ↗. In this example, we've named the gateway stagehand-example-gateway
.
const stagehand = new Stagehand({ env: "LOCAL", localBrowserLaunchOptions: { cdpUrl }, llmClient: new WorkersAIClient(env.AI, { gateway: { id: "stagehand-example-gateway" } }), });
If you want to use a model outside of Workers AI, you can configure Stagehand to use models from supported third-party providers ↗, including OpenAI and Anthropic, by providing your own credentials.
In this example, you will configure Stagehand to use OpenAI ↗. You will need an OpenAI API key. Cloudflare recommends storing your API key as a secret.
npx wrangler secret put OPENAI_API_KEY
Then, configure Stagehand with your provider, model, and API key.
const stagehand = new Stagehand({ env: "LOCAL", localBrowserLaunchOptions: { cdpUrl: endpointURLString(env.BROWSER) }, modelName: "openai/gpt-4.1", modelClientOptions: { apiKey: env.OPENAI_API_KEY, },});
AI Gateway is a service that adds observability to your AI applications. By routing your requests through AI Gateway, you can monitor and debug your AI applications.
To use AI Gateway, first create a gateway in the Cloudflare dashboard ↗. In this example, we are using OpenAI with AI Gateway ↗. Make sure to add the baseURL
as shown below, with your own Account ID and Gateway ID.
const stagehand = new Stagehand({ env: "LOCAL", localBrowserLaunchOptions: { cdpUrl: endpointURLString(env.BROWSER) }, modelName: "openai/gpt-4.1", modelClientOptions: { baseURL: `https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openai`, },});
For the full list of Stagehand methods and capabilities, refer to the official Stagehand API documentation ↗.
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Directory
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- © 2025 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark
-