One Browser, Many Clients! Browser Run Now Accepts Concurrent Connections
Hi everyone, it's Shii-chan! I found a neat update that lets you reuse browsers!
Cloudflare ChangelogWhat was announced?
In the Cloudflare Changelog, Cloudflare announced that Browser Run sessions now accept multiple concurrent connections.
The story so far
Before, a session accepted only one connection at a time. Other Workers had to wait until that connection closed.
What changes
Multiple Workers can now connect to the same browser at the same time! The announcement lists these benefits:
- Fewer new browsers to launch
- Less cold-start time
- Fewer concurrent browsers counted against your limits
Dive Deep
Each puppeteer.connect() call opens its own Chrome DevTools Protocol (CDP) connection.
To keep pages, cookies, and storage apart from other clients, create a separate browser context for each request. The example from the announcement goes like this:
const browser = await puppeteer.connect(env.MYBROWSER, sessionId);
const context = await browser.createBrowserContext();
try {
const page = await context.newPage();
await page.goto("https://example.com");
// ...
} finally {
await context.close();
await browser.disconnect(); // keep the shared browser running
}
The key part is at the end: it closes the context with context.close(), then leaves with browser.disconnect(). Because it uses disconnect() rather than close(), the shared browser keeps running.
Concurrent connections require @cloudflare/puppeteer version 1.1.0 or later. A full example is in the Reuse sessions page of the docs.
Wrap-up
- Browser Run sessions now accept multiple concurrent connections
- Before, only one connection was allowed and other Workers had to wait
- Each connection opens its own CDP connection
- A browser context per request keeps pages, cookies, and storage separate
- Requires
@cloudflare/puppeteer1.1.0 or later
This one is for developers running lots of browser automation from Workers!