### Get All Links from a Page using cURL Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt This example demonstrates how to use the cURL command-line tool to send a POST request to the Cloudflare Browser Rendering API to retrieve all links from a specified URL. It requires an account ID, API token, and the target URL as input. The output is a JSON array of links. ```bash curl -X POST 'https://api.cloudflare.com/client/v4/accounts//browser-rendering/links' \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ -d '{ "url": "https://developers.cloudflare.com/" }' ``` -------------------------------- ### Install project dependencies Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt Installs the necessary project dependencies required for the Stagehand worker environment. ```bash npm ci ``` -------------------------------- ### Extract Links from a Page using Node.js Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt This Node.js example shows how to use the `axios` library to make a POST request to the Cloudflare Browser Rendering API to get all links from a webpage. Ensure you have `axios` installed (`npm install axios`). The function takes an API token, account ID, and URL, returning a promise that resolves with the list of links. ```javascript const axios = require('axios'); async function getAllLinks(apiToken, accountId, url) { try { const response = await axios.post( `https://api.cloudflare.com/client/v4/accounts/${accountId}/browser-rendering/links`, { url }, { headers: { 'Authorization': `Bearer ${apiToken}`, 'Content-Type': 'application/json' } } ); return response.data.result; } catch (error) { console.error('Error fetching links:', error); return []; } } // Example usage: // const apiToken = 'YOUR_API_TOKEN'; // const accountId = 'YOUR_ACCOUNT_ID'; // const targetUrl = 'https://developers.cloudflare.com/'; // // getAllLinks(apiToken, accountId, targetUrl).then(links => { // console.log(links); // }); ``` -------------------------------- ### Get All Links from a Page using TypeScript SDK Source: https://developers.cloudflare.com/browser-rendering/rest-api/links-endpoint This example demonstrates how to retrieve all links from a webpage using the Cloudflare TypeScript SDK. It requires proper initialization of the SDK with account details and an API token. The function returns a promise that resolves to a JSON object containing the success status and an array of links. ```typescript import { CloudflareClient } from '@cloudflare/api'; async function getAllLinks(accountId: string, apiToken: string, url: string): Promise { const client = new CloudflareClient({ token: apiToken }); const response = await client.browserRendering.links({ accountId, url }); return response.result; } // Example usage: // const accountId = ''; // const apiToken = ''; // const url = 'https://developers.cloudflare.com/'; // getAllLinks(accountId, apiToken, url).then(links => console.log(links)); ``` -------------------------------- ### Install @cloudflare/playwright-mcp with npm, yarn, or pnpm Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt Installs the @cloudflare/playwright-mcp package as a development dependency using different package managers. ```npm npm i -D @cloudflare/playwright-mcp ``` ```yarn yarn add -D @cloudflare/playwright-mcp ``` ```pnpm pnpm add -D @cloudflare/playwright-mcp ``` -------------------------------- ### Run Development Server Source: https://developers.cloudflare.com/browser-rendering/how-to/pdf-generation Commands to start the local development environment for the Cloudflare Worker using different package managers. ```bash npx wrangler dev ``` ```bash yarn wrangler dev ``` ```bash pnpm wrangler dev ``` -------------------------------- ### Run Development Server Source: https://developers.cloudflare.com/browser-rendering/how-to/ai Command to start the local development environment for the Cloudflare Worker. ```bash npx wrangler dev ``` -------------------------------- ### Start Astro Development Server Source: https://developers.cloudflare.com/browser-rendering/how-to/og-images-astro Command to start the local development server for an Astro project. This allows you to test your Astro pages, including the OG image template, locally before deployment. ```bash npm run dev ``` -------------------------------- ### Convert URL to PDF using Cloudflare Browser Rendering Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt Demonstrates how to render a webpage as a PDF via the /pdf endpoint. Includes examples for injecting custom CSS styles using both cURL and the TypeScript SDK. ```bash curl -X POST 'https://api.cloudflare.com/client/v4/accounts//browser-rendering/pdf' \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ -d '{ "url": "https://example.com/", "addStyleTag": [ { "content": "body { font-family: Arial; }" } ] }' \ --output "output.pdf" ``` ```typescript import Cloudflare from "cloudflare"; const client = new Cloudflare({ apiToken: process.env["CLOUDFLARE_API_TOKEN"], }); const pdf = await client.browserRendering.pdf.create({ account_id: process.env["CLOUDFLARE_ACCOUNT_ID"], url: "https://example.com/", addStyleTag: [ { content: "body { font-family: Arial; }" } ] }); console.log(pdf); const content = await pdf.blob(); console.log(content); ``` -------------------------------- ### Customize OG Templates Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt Examples for enhancing OG templates with dynamic background images, custom fonts, and Tailwind CSS styling. ```astro --- const title = Astro.url.searchParams.get("title") || "Untitled"; const image = Astro.url.searchParams.get("image"); --- ``` ```astro ``` ```astro --- import "../styles/global.css"; ---

{title}

``` -------------------------------- ### Wrangler Configuration for KV Namespace and Browser Binding Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt These examples show the necessary configurations in `wrangler.jsonc` and `wrangler.toml` to set up a KV namespace binding named 'KV' and a browser binding named 'MYBROWSER' for a Cloudflare Worker project. These bindings are essential for the storage state and browser launching examples, respectively. ```jsonc { "name": "storage-state-examples", "main": "src/index.ts", "compatibility_flags": ["nodejs_compat"], // Set this to today's date "compatibility_date": "2026-03-06", "browser": { "binding": "MYBROWSER" }, "kv_namespaces": [ { "binding": "KV", "id": "" } ] } ``` ```toml name = "storage-state-examples" main = "src/index.ts" compatibility_flags = [ "nodejs_compat" ] # Set this to today's date compatibility_date = "2026-03-06" [browser] binding = "MYBROWSER" [[kv_namespaces]] binding = "KV" id = "" ``` -------------------------------- ### Install Cloudflare Puppeteer Dependency Source: https://developers.cloudflare.com/browser-rendering/how-to/pdf-generation Commands to add the @cloudflare/puppeteer package to the project as a development dependency. ```npm npm i -D @cloudflare/puppeteer ``` ```yarn yarn add -D @cloudflare/puppeteer ``` ```pnpm pnpm add -D @cloudflare/puppeteer ``` -------------------------------- ### Initialize Cloudflare Worker Project Source: https://developers.cloudflare.com/browser-rendering/how-to/ai Commands to scaffold a new Cloudflare Worker project and install necessary dependencies including Puppeteer and Zod. ```bash npm create cloudflare@latest -- browser-worker npm i @cloudflare/puppeteer npm i zod npm i zod-to-json-schema ``` -------------------------------- ### Customizing Page Headers and Footers in PDF Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt Generates a PDF with customized headers and footers using HTML templates. This example sets an A5 format, a branded header, a footer message, and enables page numbering. The `displayHeaderFooter` option must be true. ```bash curl -X POST 'https://api.cloudflare.com/client/v4/accounts//browser-rendering/pdf' \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ -d '{ \ "url": "https://example.com", \ "pdfOptions": { \ "format": "a5", \ "headerTemplate": "
brand name
", \ "displayHeaderFooter": true, \ "footerTemplate": "
This is a test message -
", \ "margin": { \ "top": "70px", \ "bottom": "70px" \ } \ } \ }' \ --output "header-footer.pdf" ``` -------------------------------- ### Convert URL to Markdown using TypeScript SDK Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt This TypeScript example shows how to use the Cloudflare SDK to convert a webpage URL into Markdown. It requires setting up the Cloudflare client with an API token and providing the account ID and URL. ```typescript import Cloudflare from "cloudflare"; const client = new Cloudflare({ apiToken: process.env["CLOUDFLARE_API_TOKEN"], }); const markdown = await client.browserRendering.markdown.create({ account_id: process.env["CLOUDFLARE_ACCOUNT_ID"], url: "https://developers.cloudflare.com/", }); console.log(markdown); ``` -------------------------------- ### POST /browser-rendering/json - With Prompt and JSON Schema Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt Captures webpage data by providing both a prompt and a JSON schema. The prompt guides the extraction process, while the JSON schema defines the expected structure of the output. ```APIDOC ## POST /browser-rendering/json ### Description Captures webpage data by providing both a prompt and a JSON schema. The prompt guides the extraction process, while the JSON schema defines the expected structure of the output. ### Method POST ### Endpoint `https://api.cloudflare.com/client/v4/accounts/CF_ACCOUNT_ID/browser-rendering/json` ### Parameters #### Request Body - **url** (string) - Required - The URL of the webpage to process. - **prompt** (string) - Required - The prompt to guide data extraction. - **response_format** (object) - Required - Defines the desired output format. - **type** (string) - Required - The type of response format, e.g., `json_schema`. - **schema** (object) - Required - The JSON schema defining the output structure. ### Request Example ```json { "url": "https://developers.cloudflare.com/", "prompt": "Get me the list of AI products", "response_format": { "type": "json_schema", "schema": { "type": "object", "properties": { "products": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string" }, "link": { "type": "string" } }, "required": [ "name" ] } } } } } } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **result** (object) - The extracted data based on the prompt and schema. #### Response Example ```json { "success": true, "result": { "products": [ { "name": "Build a RAG app", "link": "https://developers.cloudflare.com/workers-ai/tutorials/build-a-retrieval-augmented-generation-ai/" }, { "name": "Workers AI", "link": "https://developers.cloudflare.com/workers-ai/" }, { "name": "Vectorize", "link": "https://developers.cloudflare.com/vectorize/" }, { "name": "AI Gateway", "link": "https://developers.cloudflare.com/ai-gateway/" }, { "name": "AI Playground", "link": "https://playground.ai.cloudflare.com/" } ] } } ``` ``` -------------------------------- ### Configure environment variables and run script Source: https://developers.cloudflare.com/browser-rendering/how-to/og-images-astro Commands to set the necessary Cloudflare credentials and execute the generation script using the Bun runtime. ```bash export CF_ACCOUNT_ID=your_account_id export CF_API_TOKEN=your_api_token bun scripts/generate-social-cards.ts ``` -------------------------------- ### Deploying with Wrangler Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt Instructions on how to use Wrangler, a command-line tool, to deploy projects that utilize the Cloudflare Workers Browser Rendering API. ```APIDOC ## Wrangler for Browser Rendering [Wrangler](https://developers.cloudflare.com/workers/wrangler/) is a command-line tool for building with Cloudflare's developer products. Use Wrangler to deploy projects that use the Workers Browser Rendering API. ### Installation Refer to [Install and Update Wrangler](https://developers.cloudflare.com/workers/wrangler/install-and-update/) for installation instructions. ``` -------------------------------- ### Configure Wrangler with Browser Binding and R2 Bucket (TOML) Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt Sets up the Wrangler configuration file in TOML format. It includes a browser binding for headless browser interaction, an R2 bucket binding for storage, and a Durable Object binding. Requires `nodejs_compat` flag and a recent `compatibility_date`. ```toml $schema = "./node_modules/wrangler/config-schema.json" name = "rendering-api-demo" main = "src/index.js" compatibility_date = "2026-03-06" compatibility_flags = [ "nodejs_compat" ] account_id = "" [browser] binding = "MYBROWSER" [[r2_buckets]] binding = "BUCKET" bucket_name = "screenshots" preview_bucket_name = "screenshots-test" [[durable_objects.bindings]] name = "BROWSER" class_name = "Browser" [[migrations]] tag = "v1" new_sqlite_classes = [ "Browser" ] ``` -------------------------------- ### Reuse Playwright Browser Sessions in Cloudflare Workers (TypeScript) Source: https://developers.cloudflare.com/browser-rendering/playwright This example demonstrates how to optimize performance by reusing Playwright browser sessions in Cloudflare Workers. It uses `acquire` to get a session ID and then `connect` to reuse that session across multiple requests. Closing the browser with `browser.close()` disconnects from the session but keeps the session alive for subsequent reuse. This requires the `@cloudflare/playwright` package. ```typescript import { env } from "cloudflare:workers"; import { acquire, connect } from "@cloudflare/playwright"; async function reuseSameSession() { // acquires a new session const { sessionId } = await acquire(env.BROWSER); for (let i = 0; i < 5; i++) { // connects to the session that was previously acquired const browser = await connect(env.BROWSER, sessionId); // ... // this will disconnect the browser from the session, but the session will be kept alive await browser.close(); } } ``` -------------------------------- ### Convert Custom HTML to PDF Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt Shows how to generate a PDF from raw HTML strings. Supports applying custom styles and external stylesheets via the addStyleTag parameter. ```bash curl -X POST https://api.cloudflare.com/client/v4/accounts//browser-rendering/pdf \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ -d '{ "html": "Advanced Snapshot", "addStyleTag": [ { "content": "body { font-family: Arial; }" }, { "url": "https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" } ] }' \ --output "invoice.pdf" ``` -------------------------------- ### Install Cloudflare Puppeteer with pnpm Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt Installs the Cloudflare-specific fork of Puppeteer as a development dependency using pnpm. This library is essential for interacting with the Browser Rendering API. ```bash pnpm add -D @cloudflare/puppeteer ``` -------------------------------- ### Install Cloudflare Puppeteer with yarn Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt Installs the Cloudflare-specific fork of Puppeteer as a development dependency using yarn. This library is essential for interacting with the Browser Rendering API. ```bash yarn add -D @cloudflare/puppeteer ``` -------------------------------- ### Initialize Cloudflare Worker Project Source: https://developers.cloudflare.com/browser-rendering/how-to/pdf-generation Commands to scaffold a new Cloudflare Worker project using different package managers. ```npm npm create cloudflare@latest -- browser-worker ``` ```yarn yarn create cloudflare browser-worker ``` ```pnpm pnpm create cloudflare@latest browser-worker ``` -------------------------------- ### Install Cloudflare Puppeteer with npm Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt Installs the Cloudflare-specific fork of Puppeteer as a development dependency using npm. This library is essential for interacting with the Browser Rendering API. ```bash npm i -D @cloudflare/puppeteer ``` -------------------------------- ### Install @cloudflare/playwright with pnpm Source: https://developers.cloudflare.com/browser-rendering/playwright Installs the @cloudflare/playwright package as a development dependency using pnpm. This package enables browser automation within Cloudflare Workers. ```bash pnpm add -D @cloudflare/playwright ``` -------------------------------- ### Install @cloudflare/playwright with yarn Source: https://developers.cloudflare.com/browser-rendering/playwright Installs the @cloudflare/playwright package as a development dependency using yarn. This package enables browser automation within Cloudflare Workers. ```bash yarn add -D @cloudflare/playwright ``` -------------------------------- ### Install @cloudflare/playwright with npm Source: https://developers.cloudflare.com/browser-rendering/playwright Installs the @cloudflare/playwright package as a development dependency using npm. This package enables browser automation within Cloudflare Workers. ```bash npm i -D @cloudflare/playwright ``` -------------------------------- ### Create KV namespaces for browser data Source: https://developers.cloudflare.com/browser-rendering/get-started Creates production and preview KV namespaces using Wrangler to store browser output like screenshots. ```bash npx wrangler kv namespace create BROWSER_KV_DEMO npx wrangler kv namespace create BROWSER_KV_DEMO --preview ``` -------------------------------- ### Install Playwright MCP with pnpm Source: https://developers.cloudflare.com/browser-rendering/playwright/playwright-mcp Installs the Playwright MCP npm package as a development dependency using pnpm. This command is typically run in the project's root directory. ```bash pnpm add -D @cloudflare/playwright-mcp ``` -------------------------------- ### Install Playwright MCP with yarn Source: https://developers.cloudflare.com/browser-rendering/playwright/playwright-mcp Installs the Playwright MCP npm package as a development dependency using yarn. This command is typically run in the project's root directory. ```bash yarn add -D @cloudflare/playwright-mcp ``` -------------------------------- ### Handle Browser Launch/Connect Errors with try/catch Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt This JavaScript code demonstrates how to wrap `puppeteer.connect` or `puppeteer.launch` within a `try/catch` statement. This is a best practice to gracefully handle potential errors that may occur during the initialization of a headless browser session, preventing unexpected crashes. ```javascript try { // Attempt to connect or launch puppeteer const browser = await puppeteer.connect({ browserWSEndpoint: wsEndpoint, }); // ... rest of your browser interaction code } catch (error) { console.error('Error during browser connection or launch:', error); // Handle the error appropriately, e.g., retry or log detailed information } ``` -------------------------------- ### Install Playwright MCP with npm Source: https://developers.cloudflare.com/browser-rendering/playwright/playwright-mcp Installs the Playwright MCP npm package as a development dependency using npm. This command is typically run in the project's root directory. ```bash npm i -D @cloudflare/playwright-mcp ``` -------------------------------- ### Install Cloudflare Playwright Package Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt Instructions for installing the Cloudflare-specific version of the Playwright package using different package managers. This package is a fork of Playwright modified for compatibility with Cloudflare Workers and Browser Rendering. ```npm npm i -D @cloudflare/playwright ``` ```yarn yarn add -D @cloudflare/playwright ``` ```pnpm pnpm add -D @cloudflare/playwright ``` -------------------------------- ### POST /accounts/{accountId}/browser-rendering/snapshot Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt Creates a browser rendering snapshot from a provided URL or custom HTML content, allowing for detailed configuration of the rendering environment. ```APIDOC ## POST /accounts/{accountId}/browser-rendering/snapshot ### Description Creates a snapshot of a webpage or custom HTML. Supports advanced options like disabling JavaScript, custom viewports, and specific network wait conditions. ### Method POST ### Endpoint https://api.cloudflare.com/client/v4/accounts/{accountId}/browser-rendering/snapshot ### Parameters #### Path Parameters - **accountId** (string) - Required - The Cloudflare account identifier. #### Request Body - **html** (string) - Optional - Custom HTML content to render. - **url** (string) - Optional - The URL to capture. - **setJavaScriptEnabled** (boolean) - Optional - Whether to enable JavaScript execution. - **screenshotOptions** (object) - Optional - Configuration for the screenshot (e.g., fullPage). - **viewport** (object) - Optional - Dimensions and scale factor (width, height, deviceScaleFactor). - **gotoOptions** (object) - Optional - Navigation behavior (waitUntil, timeout). - **userAgent** (string) - Optional - Custom user agent string. ### Request Example { "html": "Advanced Snapshot", "setJavaScriptEnabled": false, "screenshotOptions": { "fullPage": true }, "viewport": { "width": 1200, "height": 800 }, "gotoOptions": { "waitUntil": "domcontentloaded", "timeout": 30000 } } ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **result** (object) - Contains the rendered content and base-64 encoded screenshot. #### Response Example { "success": true, "result": { "screenshot": "AdvancedBase64Screenshot", "content": "Advanced Snapshot" } } ``` -------------------------------- ### Install Cloudflare's Puppeteer fork using npm, yarn, or pnpm Source: https://developers.cloudflare.com/browser-rendering/workers-bindings/reuse-sessions Commands to install the Cloudflare-specific fork of Puppeteer as a development dependency in the 'browser-worker' project. This library is essential for interacting with headless browsers. ```bash npm i -D @cloudflare/puppeteer ``` ```bash yarn add -D @cloudflare/puppeteer ``` ```bash pnpm add -D @cloudflare/puppeteer ``` -------------------------------- ### Browser Rendering API Response Example Source: https://developers.cloudflare.com/browser-rendering/rest-api/json-endpoint This is an example of a successful response from the Browser Rendering API when using a custom AI model to extract headings. The JSON object contains the extracted 'h1' and 'h2' headings from the target URL. ```json { "success": true, "result": { "h1": "Heading 1", "h2": "Heading 2" } } ``` -------------------------------- ### Create custom HTML snapshot via REST API Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt Demonstrates how to POST custom HTML to the Browser Rendering API with specific configurations like disabled JavaScript, custom viewport dimensions, and wait conditions. Returns a base-64 encoded screenshot and the rendered content. ```bash curl -X POST 'https://api.cloudflare.com/client/v4/accounts//browser-rendering/snapshot' \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ -d '{ "html": "Advanced Snapshot", "setJavaScriptEnabled": false, "screenshotOptions": { "fullPage": true }, "viewport": { "width": 1200, "height": 800 }, "gotoOptions": { "waitUntil": "domcontentloaded", "timeout": 30000 } }' ``` ```json { "success": true, "result": { "screenshot": "AdvancedBase64Screenshot", "content": "Advanced Snapshot" } } ``` -------------------------------- ### Extract links from a webpage using Browser Rendering API Source: https://developers.cloudflare.com/browser-rendering/rest-api/links-endpoint Demonstrates how to initialize the Cloudflare SDK and use the browser rendering service to extract links from a specified URL. This requires an API token and account ID configured in the environment. ```javascript import Cloudflare from "cloudflare"; const client = new Cloudflare({ apiToken: process.env["CLOUDFLARE_API_TOKEN"], }); const links = await client.browserRendering.links.create({ account_id: process.env["CLOUDFLARE_ACCOUNT_ID"], url: "https://developers.cloudflare.com/", }); console.log(links); ``` -------------------------------- ### GET /links Source: https://developers.cloudflare.com/browser-rendering/rest-api/links-endpoint Retrieves all links from a webpage. You can provide either a URL or HTML content to process. ```APIDOC ## GET /links ### Description Retrieves all links from a webpage. It can be used to extract all links from a page, including those that are hidden. ### Method GET ### Endpoint `https://api.cloudflare.com/client/v4/accounts//browser-rendering/links` ### Parameters #### Query Parameters - **url** (string) - Required - The URL of the webpage to process. - **html** (string) - Required - The HTML content of the webpage to process. *Note: You must provide either `url` or `html`.* ### Request Example ``` GET https://api.cloudflare.com/client/v4/accounts/YOUR_ACCOUNT_ID/browser-rendering/links?url=https://example.com ``` ### Response #### Success Response (200) - **links** (array) - An array of objects, where each object represents a link found on the page. - **url** (string) - The URL of the link. - **text** (string) - The visible text of the link. - **type** (string) - The type of link (e.g., 'internal', 'external', 'anchor'). #### Response Example ```json { "success": true, "errors": [], "messages": [], "result": { "links": [ { "url": "https://example.com/about", "text": "About Us", "type": "internal" }, { "url": "https://example.com/contact", "text": "Contact", "type": "internal" } ] } } ``` ``` -------------------------------- ### GET /puppeteer/sessions Source: https://developers.cloudflare.com/browser-rendering/puppeteer Retrieves a list of all currently running browser sessions. ```APIDOC ## GET /puppeteer/sessions ### Description Lists the current running browser sessions. Sessions with an active `connectionId` are currently in use by a worker. ### Method GET ### Endpoint /puppeteer/sessions ### Response #### Success Response (200) - **sessionId** (string) - Unique identifier for the session - **startTime** (number) - Timestamp of session creation - **connectionId** (string, optional) - ID of the active worker connection - **connectionStartTime** (number, optional) - Timestamp when the connection started #### Response Example [ { "connectionId": "2a2246fa-e234-4dc1-8433-87e6cee80145", "connectionStartTime": 1711621704607, "sessionId": "478f4d7d-e943-40f6-a414-837d3736a1dc", "startTime": 1711621703708 } ] ``` -------------------------------- ### Session Reuse Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt Demonstrates how to reuse browser sessions for improved performance by acquiring a session and then connecting to it for multiple requests. ```APIDOC ## Session Reuse ### Description Improves Worker performance by reusing browser sessions. This involves acquiring a session once and then connecting to it for subsequent requests, keeping the browser open. ### Method `acquire` and `connect` from `@cloudflare/playwright` ### Endpoint N/A (Client-side Worker code) ### Parameters None directly for the reuse logic, but relies on `env.BROWSER`. ### Request Example ```javascript import { env } from "cloudflare:workers"; import { acquire, connect } from "@cloudflare/playwright"; async function reuseSameSession() { // acquires a new session const { sessionId } = await acquire(env.BROWSER); for (let i = 0; i < 5; i++) { // connects to the session that was previously acquired const browser = await connect(env.BROWSER, sessionId); // ... perform actions with the browser ... // this will disconnect the browser from the session, but the session will be kept alive await browser.close(); } } ``` ### Response N/A (This is a code pattern, not a direct API response) ``` -------------------------------- ### GET /puppeteer/limits Source: https://developers.cloudflare.com/browser-rendering/puppeteer Retrieves current account limits and active session status. ```APIDOC ## GET /puppeteer/limits ### Description Returns information regarding concurrent session limits and rate-limiting status for launching new browsers. ### Method GET ### Endpoint /puppeteer/limits ### Response #### Success Response (200) - **activeSessions** (array) - List of currently open session objects - **maxConcurrentSessions** (number) - Maximum allowed concurrent sessions - **allowedBrowserAcquisitions** (number) - Number of browsers that can be acquired - **timeUntilNextAllowedBrowserAcquisition** (number) - Wait time in milliseconds until next allowed launch #### Response Example { "activeSessions": [{"id": "478f4d7d-e943-40f6-a414-837d3736a1dc"}], "maxConcurrentSessions": 2, "allowedBrowserAcquisitions": 1, "timeUntilNextAllowedBrowserAcquisition": 0 } ``` -------------------------------- ### Handle Browser Instance Limit with Retry-After (Workers Bindings) Source: https://developers.cloudflare.com/browser-rendering/llms-full.txt Illustrates how to manage rate limiting when launching browser instances via Workers Bindings. If a 429 error occurs, it extracts the 'Retry-After' value and retries launching the browser after the specified delay. This ensures continued operation despite temporary limits. ```javascript import puppeteer from "@cloudflare/puppeteer"; try { const browser = await puppeteer.launch(env.MYBROWSER); const page = await browser.newPage(); await page.goto("https://example.com"); const content = await page.content(); await browser.close(); } catch (error) { if (error.status === 429) { const retryAfter = error.headers.get("Retry-After"); console.log( `Browser instance limit reached. Waiting ${retryAfter} seconds`, ); await new Promise((resolve) => setTimeout(resolve, retryAfter * 1000)); // Retry launching browser const browser = await puppeteer.launch(env.MYBROWSER); } } ``` -------------------------------- ### Configure Wait Until Option for REST API Source: https://developers.cloudflare.com/browser-rendering/faq Demonstrates how to configure the 'waitUntil' parameter in the REST API to ensure dynamic content is loaded before capture. This helps resolve issues with missing content on JavaScript-heavy pages. ```json { "url": "https://example.com", "goToOptions": { "waitUntil": "networkidle2" } } ```