Can Stagehand work on a Cloudflare worker + Durable object setup?
We're considering using Stagehand in a Cloudflare Worker + Durable Object (DO) setup. The Agent, built with agent-sdk, manages WebSocket connections, session state, and interacts with Browserbase to automate browser sessions.
Questions
- Is Stagehand compatible with Cloudflare Worker + Durable Object environments?
- Any best practices or limitations we should consider?
Currently, I am getting this error which I think occurs because of trying to load a native .node module, which is not supported in Cloudflare Workers.
Cloudflare has its own fork of Playwright: https://github.com/cloudflare/playwright, which can be spun up inside a Worker. They also provide their own browser automation solution: https://developers.cloudflare.com/browser-rendering/
I tried running Stagehand on a Cloudflare Worker a few months ago, but it wasn’t possible because Workers are not fully compatible with Node.js and therefore lack the fs module. However, this may change soon: https://github.com/cloudflare/workerd/pull/3796.
So, long story short, as of now, you either use their solution or host it elsewhere.
Cloudflare has its own fork of Playwright: https://github.com/cloudflare/playwright, which can be spun up inside a Worker. They also provide their own browser automation solution: https://developers.cloudflare.com/browser-rendering/
I tried running Stagehand on a Cloudflare Worker a few months ago, but it wasn’t possible because Workers are not fully compatible with Node.js and therefore lack the
fsmodule. However, this may change soon: cloudflare/workerd#3796.So, long story short, as of now, you either use their solution or host it elsewhere.
I used 「alias」field in wrangler.jsonc: { ..., "alias": { "fs": "./polyfill/fs.js" } } And used AI to generate polyfill/fs.js to provides a minimal implementation of the Node.js fs module. I don't know if this is equally effective for node:promise.
@LiuN1an are you saying you did make it work this way?
FYI, I experimented w/ this and got to a working version by forking @cloudflare/playwright: https://github.com/cloudflare/playwright/pull/59 and forking browserbase/stagehand to replace its use of playwright with @cloudflare/playwright.
This works beautifully but needs a Cloudflare compatibility flag for it to make it to production due to the size of the Websocket messages, which isn't yet available on production https://github.com/cloudflare/workerd/issues/4649
Revisiting this thread to say that Cloudflare has officially listed the limitation on websocket message sizes that was causing incompatibility, so with Stagehand v3 we should now be able to see this code base work in a Cloudflare Workers environment with minimal modifications. Thoughts @danamajid ?
Haven't looked into this lately but I did see Cloudflare recently added support for Stagehand through Workers AI; https://developers.cloudflare.com/browser-rendering/stagehand/