This example demonstrates how to run integrate Stagehand in a Cloudflare Worker using Vite to extract information from a movie from The Movie Database.
It uses Workers AI @cf/meta/llama-3.3-70b-instruct-fp8-fast as the model by default.
- Install dependencies:
npm ci- Run in development mode:
npm run dev- Deploy to Cloudflare Workers:
npm run deployOnce deployed, you can interact with the Worker using these URL patterns:
https://<your-worker>.workers.dev
This will search for a movie and return a page with the movie information and a screenshot.
Under the hood, it uses Cloudflare Workers AI, more specifically llama-3.3-70b-instruct-fp8-fast. For that, we created a custom LLMClient.
You can use another model, like OpenAI. For that, you need a OpenAI API key (it's strongly recommended to keep it as a https://developers.cloudflare.com/workers/configuration/secrets/).
You can then configure Stagehand to use OpenAI:
// Get the CDP URL for browser binding
const cdpUrl = cdpUrl: endpointURLString("BROWSER");
const stagehand = new Stagehand({
env: "LOCAL",
localBrowserLaunchOptions: { cdpUrl },
modelName: "openai/gpt-4.1",
modelClientOptions: {
apiKey: env.OPENAI_API_KEY,
},
});You can configure Stagehand to use Cloudflare AI Gateway too.
For instance, if you use OpenAI, after creating a gateway (its name corresponds to the AI_GATEWAY_ID), you can configure it like this:
const stagehand = new Stagehand({
env: "LOCAL",
localBrowserLaunchOptions: { cdpUrl: endpointURLString("BROWSER") },
modelName: "openai/gpt-4.1",
modelClientOptions: {
apiKey: env.OPENAI_API_KEY,
baseURL: `https://gateway.ai.cloudflare.com/v1/${env.CLOUDFLARE_ACCOUNT_ID}/${env.AI_GATEWAY_ID}/openai`,
},
});It's important that the vite.config.ts file has the following alias:
import { defineConfig } from "vite";
import { cloudflare } from "@cloudflare/vite-plugin";
export default defineConfig({
plugins: [cloudflare(), /* eventually other plugins like react */],
resolve: {
alias: {
'playwright': '@cloudflare/playwright',
},
},
});It's also possible to use Stagehand without Vite. For that, just ensure that wrangler configuration file has the following module alias:
{
// ...
"alias": {
"playwright": "@cloudflare/playwright"
}
}