Browser Rendering
The browser binding starts a headless browser on Cloudflare, which you drive with Cloudflare's build of Puppeteer. Declare the binding:
{
"name": "my-app",
"ai": { "binding": "AI" },
"vectorize": [{ "binding": "VECTORIZE", "index_name": "docs" }],
"browser": { "binding": "BROWSER" },
}
browser is one of the kinds the typed env does not describe: env.BROWSER is unknown, and typegen warns once (the wrangler config binds "browser", which Hamur does not type; its bindings are typed unknown on event.runtime.env). Install @cloudflare/puppeteer in the app and pass the binding to puppeteer.launch; the handler narrows env.BROWSER the way the other recipes narrow their bindings.
import puppeteer from "@cloudflare/puppeteer"
import { createError, defineHandler, getQuery } from "hamur/server"
import type { HamurEvent } from "hamur/server"
interface Env {
BROWSER: unknown
}
const bindings = (event: HamurEvent): Env => {
const env = event.runtime.env as unknown as Partial<Env> | undefined
if (!env?.BROWSER) throw createError({ status: 501, message: "The BROWSER binding is not configured" })
return env as Env
}
export const screenshot = defineHandler({
route: "/api/screenshot",
method: "GET",
raw: true,
async handler(_, { event }) {
const { BROWSER } = bindings(event)
const url = String(getQuery(event).url ?? "https://example.com")
const browser = await puppeteer.launch(BROWSER)
try {
const page = await browser.newPage()
await page.goto(url, { waitUntil: "load" })
return new Response(await page.screenshot({ type: "png" }), { headers: { "content-type": "image/png" } })
} finally {
await browser.close()
}
},
})
The sample's @cloudflare/puppeteer types are a minimal declaration, so the file compiles in the documentation without the package:
declare module "@cloudflare/puppeteer" {
interface Page {
goto(url: string, options?: { waitUntil?: "load" | "domcontentloaded" | "networkidle0" }): Promise<unknown>
screenshot(options?: { type?: "png" | "jpeg" }): Promise<ArrayBuffer>
}
interface Browser {
newPage(): Promise<Page>
close(): Promise<void>
}
const puppeteer: { launch(binding: unknown): Promise<Browser> }
export default puppeteer
}
Drop that declaration once the package is installed. A browser session is a billed, limited resource: close it in a finally, as the sample does, and guard the route. Browser Rendering is not available in hamur dev, where env.BROWSER is absent and the handler answers 501.