Deploy a Browser Rendering Worker with Durable Objects
Last reviewed: 12 months ago
By following this guide, you will create a Worker that uses the Browser Rendering API along with Durable Objects to take screenshots from web pages and store them in R2.
Using Durable Objects to persist browser sessions improves performance by eliminating the time that it takes to spin up a new browser session. Since Durable Objects re-uses sessions, it reduces the number of concurrent sessions needed.
Use a Node version manager like Volta ↗ or nvm ↗ to avoid permission issues and change Node.js versions. Wrangler, discussed later in this guide, requires a Node version of 16.17.0 or later.
1. Create a Worker project
Cloudflare Workers provides a serverless execution environment that allows you to create new applications or augment existing ones without configuring or maintaining infrastructure. Your Worker application is a container to interact with a headless browser to do actions, such as taking screenshots.
Create a new Worker project named browser-worker by running:
Select Purchase Workers Paid and complete the payment process to enable Durable Objects.
3. Install Puppeteer
In your browser-worker directory, install Cloudflare’s fork of Puppeteer:
4. Create a R2 bucket
Create two R2 buckets, one for production, and one for development.
Note that bucket names must be lowercase and can only contain dashes.
To check that your buckets were created, run:
After running the list command, you will see all bucket names, including the ones you have just created.
5. Configure wrangler.toml
Configure your browser-worker project’s wrangler.toml file by adding a browser binding and a Node.js compatibility flag. Browser bindings allow for communication between a Worker and a headless browser which allows you to do actions such as taking a screenshot, generating a PDF and more.
Update your wrangler.toml configuration file with the Browser Rendering API binding, the R2 bucket you created and a Durable Object:
6. Code
The code below uses Durable Object to instantiate a browser using Puppeteer. It then opens a series of web pages with different resolutions, takes a screenshot of each, and uploads it to R2.
The Durable Object keeps a browser session open for 60 seconds after last use. If a browser session is open, any requests will re-use the existing session rather than creating a new one. Update your Worker code by copy and pasting the following:
7. Test
Run npx wrangler dev --remote to test your Worker remotely before deploying to Cloudflare’s global network. Local mode support does not exist for Browser Rendering so --remote is required.
8. Deploy
Run npx wrangler deploy to deploy your Worker to the Cloudflare global network.