|
| 1 | +--- |
| 2 | +pcx_content_type: concept |
| 3 | +title: Stagehand |
| 4 | +description: Deploy a Stagehand server that uses Browser Rendering to provide browser automation capabilities to your agents. |
| 5 | +sidebar: |
| 6 | + order: 7 |
| 7 | + badge: Beta |
| 8 | +--- |
| 9 | + |
| 10 | +import { |
| 11 | + Render, |
| 12 | + WranglerConfig, |
| 13 | + TabItem, |
| 14 | + Tabs, |
| 15 | + PackageManagers, |
| 16 | + Details, |
| 17 | +} from "~/components"; |
| 18 | + |
| 19 | +[Stagehand](https://www.stagehand.dev/) 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. |
| 20 | + |
| 21 | +This guide shows you how to deploy a [Worker](/workers/) that uses Stagehand, Browser Rendering, and [Workers AI](/workers-ai/) to automate a web task. |
| 22 | + |
| 23 | +## Use Stagehand in a Worker with Workers AI |
| 24 | + |
| 25 | +In this example, you will use Stagehand to search for a movie on this [example movie directory](https://demo.playwright.dev/movies), extract its details (title, year, rating, duration, and genre), and return the information along with a screenshot of the webpage. |
| 26 | +<Details header="See an example of the result"> </Details> |
| 27 | + |
| 28 | +If instead you want to skip the steps and get started right away, select **Deploy to Cloudflare** below. |
| 29 | + |
| 30 | +[](https://deploy.workers.cloudflare.com/?url=https://github.com/cloudflare/playwright/tree/main/packages/playwright-cloudflare/examples/stagehand) |
| 31 | + |
| 32 | +After you deploy, you can interact with the Worker using this URL pattern: |
| 33 | +``` |
| 34 | +https://<your-worker>.workers.dev |
| 35 | +``` |
| 36 | + |
| 37 | +### 1. Set up your project |
| 38 | + |
| 39 | +Install the necessary dependencies: |
| 40 | + ```bash |
| 41 | + npm ci |
| 42 | + ``` |
| 43 | + |
| 44 | +### 2. Configure your Worker |
| 45 | + |
| 46 | +Update your wrangler configuration file to include the bindings for Browser Rendering and [Workers AI](/workers-ai/): |
| 47 | + <WranglerConfig> |
| 48 | + ```jsonc |
| 49 | + { |
| 50 | + "name": "stagehand-example", |
| 51 | + "main": "src/index.ts", |
| 52 | + "compatibility_flags": ["nodejs_compat"], |
| 53 | + "compatibility_date": "2025-09-17", |
| 54 | + "observability": { |
| 55 | + "enabled": true |
| 56 | + }, |
| 57 | + "browser": { |
| 58 | + "binding": "BROWSER" |
| 59 | + }, |
| 60 | + "ai": { |
| 61 | + "binding": "AI" |
| 62 | + } |
| 63 | + } |
| 64 | + ``` |
| 65 | + </WranglerConfig> |
| 66 | + |
| 67 | +If you are using the [Cloudflare Vite plugin](https://developers.cloudflare.com/workers/vite-plugin/), you need to include the following [alias](https://vite.dev/config/shared-options.html#resolve-alias) in `vite.config.ts`: |
| 68 | + |
| 69 | + |
| 70 | +```ts |
| 71 | +export default defineConfig({ |
| 72 | + // ... |
| 73 | + resolve: { |
| 74 | + alias: { |
| 75 | + 'playwright': '@cloudflare/playwright', |
| 76 | + }, |
| 77 | + }, |
| 78 | +}); |
| 79 | +``` |
| 80 | + |
| 81 | +If you are not using the Cloudflare Vite plugin, you need to include the following [module alias](https://developers.cloudflare.com/workers/wrangler/configuration/#module-aliasing) to the wrangler configuration: |
| 82 | + |
| 83 | +```jsonc |
| 84 | +{ |
| 85 | + // ... |
| 86 | + "alias": { |
| 87 | + "playwright": "@cloudflare/playwright" |
| 88 | + } |
| 89 | +} |
| 90 | +``` |
| 91 | + |
| 92 | +### 3. Write the Worker code |
| 93 | + |
| 94 | +Copy [workersAIClient.ts](https://github.com/cloudflare/playwright/blob/main/packages/playwright-cloudflare/examples/stagehand/src/worker/workersAIClient.ts) to your project. |
| 95 | + |
| 96 | +Then, in your Worker code, import the `workersAIClient.ts` file and use it to configure a new `Stagehand` instance: |
| 97 | + |
| 98 | + ```ts title="src/index.ts" |
| 99 | + |
| 100 | + import { Stagehand } from "@browserbasehq/stagehand"; |
| 101 | + import { z } from "zod"; |
| 102 | + import { endpointURLString } from "@cloudflare/playwright"; |
| 103 | + import { WorkersAIClient } from "./workersAIClient"; |
| 104 | + |
| 105 | + export default { |
| 106 | + async fetch(request: Request, env: Env) { |
| 107 | + if (new URL(request.url).pathname !== "/") |
| 108 | + return new Response("Not found", { status: 404 }); |
| 109 | + |
| 110 | + const stagehand = new Stagehand({ |
| 111 | + env: "LOCAL", |
| 112 | + localBrowserLaunchOptions: { cdpUrl: endpointURLString(env.BROWSER) }, |
| 113 | + llmClient: new WorkersAIClient(env.AI), |
| 114 | + verbose: 1, |
| 115 | + }); |
| 116 | + |
| 117 | + await stagehand.init(); |
| 118 | + const page = stagehand.page; |
| 119 | + |
| 120 | + await page.goto('https://demo.playwright.dev/movies'); |
| 121 | + |
| 122 | + // if search is a multi-step action, stagehand will return an array of actions it needs to act on |
| 123 | + const actions = await page.observe('Search for "Furiosa"'); |
| 124 | + for (const action of actions) |
| 125 | + await page.act(action); |
| 126 | + |
| 127 | + await page.act('Click the search result'); |
| 128 | + |
| 129 | + // normal playwright functions work as expected |
| 130 | + await page.waitForSelector('.info-wrapper .cast'); |
| 131 | + |
| 132 | + let movieInfo = await page.extract({ |
| 133 | + instruction: 'Extract movie information', |
| 134 | + schema: z.object({ |
| 135 | + title: z.string(), |
| 136 | + year: z.number(), |
| 137 | + rating: z.number(), |
| 138 | + genres: z.array(z.string()), |
| 139 | + duration: z.number().describe("Duration in minutes"), |
| 140 | + }), |
| 141 | + }); |
| 142 | + |
| 143 | + await stagehand.close(); |
| 144 | + |
| 145 | + return Response.json(movieInfo); |
| 146 | + }, |
| 147 | + }; |
| 148 | + ``` |
| 149 | + |
| 150 | +### 4. Build the project |
| 151 | + |
| 152 | + ```bash |
| 153 | + npm run build |
| 154 | + ``` |
| 155 | +### 5. Deploy to Cloudflare Workers |
| 156 | + |
| 157 | +After you deploy, you can interact with the Worker using this URL pattern: |
| 158 | +``` |
| 159 | +https://<your-worker>.workers.dev |
| 160 | +``` |
| 161 | + |
| 162 | + ```bash |
| 163 | + npm run deploy |
| 164 | + ``` |
| 165 | + |
| 166 | +## Use Cloudflare AI Gateway with Workers AI |
| 167 | + |
| 168 | +[AI Gateway](/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. |
| 169 | + |
| 170 | +To use AI Gateway with a third-party model, first create a gateway in the [Cloudflare dashboard](https://dash.cloudflare.com/?to=/:account/workers/ai-gateway). In this example, we've named the gateway `stagehand-example-gateway`. |
| 171 | + |
| 172 | +```typescript |
| 173 | +const stagehand = new Stagehand({ |
| 174 | + env: "LOCAL", |
| 175 | + localBrowserLaunchOptions: { cdpUrl }, |
| 176 | + llmClient: new WorkersAIClient(env.AI, { |
| 177 | + gateway: { |
| 178 | + id: "stagehand-example-gateway" |
| 179 | + } |
| 180 | + }), |
| 181 | + }); |
| 182 | +``` |
| 183 | + |
| 184 | +## Use a third-party model |
| 185 | + |
| 186 | +If you want to use a model outside of Workers AI, you can configure Stagehand to use models from supported [third-party providers](https://docs.stagehand.dev/configuration/models#supported-providers), including OpenAI and Anthropic, by providing your own credentials. |
| 187 | + |
| 188 | +In this example, you will configure Stagehand to use [OpenAI](https://openai.com/). You will need an OpenAI API key. Cloudflare recommends storing your API key as a [secret](/workers/configuration/secrets/). |
| 189 | + |
| 190 | +```bash |
| 191 | + npx wrangler secret put OPENAI_API_KEY |
| 192 | + ``` |
| 193 | + |
| 194 | +Then, configure Stagehand with your provider, model, and API key. |
| 195 | + |
| 196 | +```typescript |
| 197 | +const stagehand = new Stagehand({ |
| 198 | + env: "LOCAL", |
| 199 | + localBrowserLaunchOptions: { cdpUrl: endpointURLString(env.BROWSER) }, |
| 200 | + modelName: "openai/gpt-4.1", |
| 201 | + modelClientOptions: { |
| 202 | + apiKey: env.OPENAI_API_KEY, |
| 203 | + }, |
| 204 | +}); |
| 205 | +``` |
| 206 | + |
| 207 | +## Use Cloudflare AI Gateway with a third-party model |
| 208 | + |
| 209 | +[AI Gateway](/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. |
| 210 | + |
| 211 | +To use AI Gateway, first create a gateway in the [Cloudflare dashboard](https://dash.cloudflare.com/?to=/:account/workers/ai-gateway). In this example, we are using [OpenAI with AI Gateway](https://developers.cloudflare.com/ai-gateway/usage/providers/openai/). Make sure to add the `baseURL` as shown below, with your own Account ID and Gateway ID. |
| 212 | + |
| 213 | +```typescript |
| 214 | +const stagehand = new Stagehand({ |
| 215 | + env: "LOCAL", |
| 216 | + localBrowserLaunchOptions: { cdpUrl: endpointURLString(env.BROWSER) }, |
| 217 | + modelName: "openai/gpt-4.1", |
| 218 | + modelClientOptions: { |
| 219 | + baseURL: `https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openai`, |
| 220 | + }, |
| 221 | +}); |
| 222 | +``` |
| 223 | + |
| 224 | +## Stagehand API |
| 225 | +For the full list of Stagehand methods and capabilities, refer to the official [Stagehand API documentation](https://docs.stagehand.dev/first-steps/introduction). |
0 commit comments