Cloudflare Workers run JavaScript on 300+ edge locations worldwide. But they run on V8 isolates — not containers, not VMs. There's no filesystem, no native binaries, no way to install Chromium, no subprocess spawning. Cloudflare's own Browser Rendering product exists (we wrote a detailed comparison), but it requires a Workers Paid plan, manages browser sessions you need to babysit, enforces concurrent session limits, and adds complexity that most screenshot workflows don't need. ScreenshotRun reduces everything to a single fetch() call from your Worker. The rendering happens on our servers. Your Worker stays fast, small, stateless, and cheap to run.
For a broader look at serverless screenshot patterns across Lambda, Vercel, and other platforms, see the serverless screenshots guide. This page focuses on Workers-specific architecture: R2 storage, KV caching, D1 metadata, Cron Triggers, Queues.
Why Browser Rendering Isn't Always the Answer
Cloudflare Browser Rendering (now called Browser Run) gives you a Puppeteer-compatible API inside Workers. Sounds perfect until you hit the constraints. You need a Workers Paid plan ($5/month minimum). Each account gets a limited number of concurrent browser sessions. Cold starts for browser sessions add 1-3 seconds because Cloudflare spins up an actual Chromium instance on their infrastructure. And you're writing Puppeteer automation code — page.goto(), page.waitForSelector(), page.screenshot() — inside a Worker that was designed for lightweight request handling.
The real friction shows up in production. Cookie consent banners need custom dismiss logic for every banner framework (OneTrust, Cookiebot, the dozens of custom implementations). Bot detection systems flag the headless browser. Lazy-loaded images below the fold render as blank space unless you script the scroll. Each of these problems requires its own workaround, tested against hundreds of sites. An API that already solved them saves you from maintaining that code yourself.
When does Browser Rendering make sense? If you need to interact with pages (fill forms, click buttons, scrape dynamic content), a browser is the right tool. For screenshot capture, it's overhead.
Basic Worker Handler
The minimal integration. A Worker receives a request with a URL parameter, calls the ScreenshotRun API, returns the screenshot URL as JSON.
// src/index.ts — Cloudflare Worker
export interface Env {
SCREENSHOTRUN_API_KEY: string;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const { searchParams } = new URL(request.url);
const url = searchParams.get('url');
if (!url) {
return Response.json({ error: 'url parameter required' }, { status: 400 });
}
const params = new URLSearchParams({
url,
format: 'webp',
width: '1280',
height: '800',
block_cookies: 'true',
block_ads: 'true',
});
const res = await fetch(
`https://api.screenshotrun.com/v1/screenshots/capture?${params}`,
{ headers: { Authorization: `Bearer ${env.SCREENSHOTRUN_API_KEY}` } }
);
if (!res.ok) {
return Response.json({ error: 'Capture failed' }, { status: 502 });
}
const data: any = await res.json();
return Response.json({
screenshot_url: data.screenshot_url,
captured_at: new Date().toISOString(),
});
},
};
This Worker uses zero external dependencies. The fetch API is native to the Workers runtime. Deploy with wrangler deploy and the entire package weighs under 5 KB. The API call's network wait counts as wall time, not CPU time, so you stay well within the free plan's 10ms CPU limit.
Wrangler Configuration
Store your API key as a secret (never in wrangler.toml as plaintext). The bindings section connects your Worker to Cloudflare services like R2 buckets, KV namespaces, D1 databases.
# wrangler.toml
name = "screenshot-worker"
main = "src/index.ts"
compatibility_date = "2024-09-23"
[vars]
SCREENSHOT_FORMAT = "webp"
DEFAULT_WIDTH = "1280"
# R2 bucket for storing screenshots
[[r2_buckets]]
binding = "SCREENSHOTS"
bucket_name = "screenshots-prod"
# KV namespace for caching
[[kv_namespaces]]
binding = "CACHE"
id = "abc123def456"
# D1 database for metadata
[[d1_databases]]
binding = "DB"
database_name = "screenshot-meta"
database_id = "xyz789"
Add the API key with wrangler secret put SCREENSHOTRUN_API_KEY. Wrangler prompts for the value, encrypts it, stores it in Cloudflare's secret management, and makes it available as env.SCREENSHOTRUN_API_KEY at runtime. The key never appears in your repo or config files.
Cache Screenshots in KV
Workers KV is a global key-value store with read latency under 10ms at the edge. Use it to cache screenshot URLs so repeated requests for the same page return instantly without calling the API again.
// src/cached-capture.ts
export interface Env {
SCREENSHOTRUN_API_KEY: string;
CACHE: KVNamespace;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const { searchParams } = new URL(request.url);
const url = searchParams.get('url');
if (!url) return Response.json({ error: 'url required' }, { status: 400 });
const cacheKey = `screenshot:${url}`;
const cached = await env.CACHE.get(cacheKey);
if (cached) {
return Response.json(JSON.parse(cached), {
headers: { 'X-Cache': 'HIT' },
});
}
const params = new URLSearchParams({
url,
format: 'webp',
width: '1280',
block_ads: 'true',
});
const res = await fetch(
`https://api.screenshotrun.com/v1/screenshots/capture?${params}`,
{ headers: { Authorization: `Bearer ${env.SCREENSHOTRUN_API_KEY}` } }
);
if (!res.ok) {
return Response.json({ error: 'Capture failed' }, { status: 502 });
}
const data: any = await res.json();
const result = { screenshot_url: data.screenshot_url, captured_at: new Date().toISOString() };
// Cache for 1 hour (3600 seconds)
await env.CACHE.put(cacheKey, JSON.stringify(result), { expirationTtl: 3600 });
return Response.json(result, {
headers: { 'X-Cache': 'MISS' },
});
},
};
KV's eventual consistency model means a write in one location propagates globally within 60 seconds. For screenshot caching, that's fine — a 60-second window where two edge locations both call the API for the same URL is acceptable. The expirationTtl parameter handles automatic cleanup. No cleanup code needed.
Store Screenshots in R2
R2 is Cloudflare's S3-compatible object storage with zero egress fees. Store the actual screenshot files in R2 when you need a permanent archive, not just a cached URL. This pattern works for compliance captures, visual regression baselines, portfolio thumbnails.
// src/r2-capture.ts
export interface Env {
SCREENSHOTRUN_API_KEY: string;
SCREENSHOTS: R2Bucket;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const { searchParams } = new URL(request.url);
const url = searchParams.get('url');
if (!url) return Response.json({ error: 'url required' }, { status: 400 });
const params = new URLSearchParams({
url,
format: 'webp',
width: '1920',
height: '1080',
full_page: 'true',
block_cookies: 'true',
block_ads: 'true',
response_type: 'image',
});
const res = await fetch(
`https://api.screenshotrun.com/v1/screenshots/capture?${params}`,
{ headers: { Authorization: `Bearer ${env.SCREENSHOTRUN_API_KEY}` } }
);
if (!res.ok) {
return Response.json({ error: 'Capture failed' }, { status: 502 });
}
const hostname = new URL(url).hostname.replace(/\./g, '-');
const key = `captures/${hostname}/${Date.now()}.webp`;
await env.SCREENSHOTS.put(key, res.body, {
httpMetadata: { contentType: 'image/webp' },
customMetadata: { sourceUrl: url, capturedAt: new Date().toISOString() },
});
return Response.json({ key, stored: true });
},
};
R2 charges nothing for egress. Store a million screenshots and serve them through a custom domain or Cloudflare's public bucket URL without worrying about bandwidth bills. That's the primary advantage over AWS S3, where egress at $0.09/GB adds up fast for image-heavy workloads. The full page screenshot feature captures entire scrollable pages, producing larger files where egress savings matter most.
Track Metadata in D1
D1 is Cloudflare's edge SQLite database. Use it to store capture metadata (source URL, timestamp, file size, R2 key) so you can query your screenshot archive without scanning the R2 bucket.
// src/d1-metadata.ts
export interface Env {
SCREENSHOTRUN_API_KEY: string;
SCREENSHOTS: R2Bucket;
DB: D1Database;
}
async function recordCapture(db: D1Database, url: string, key: string, size: number) {
await db.prepare(
'INSERT INTO captures (url, r2_key, file_size, captured_at) VALUES (?, ?, ?, ?)'
).bind(url, key, size, new Date().toISOString()).run();
}
async function getHistory(db: D1Database, url: string) {
return db.prepare(
'SELECT r2_key, file_size, captured_at FROM captures WHERE url = ? ORDER BY captured_at DESC LIMIT 30'
).bind(url).all();
}
// D1 schema (run once via wrangler d1 execute)
// CREATE TABLE captures (
// id INTEGER PRIMARY KEY AUTOINCREMENT,
// url TEXT NOT NULL,
// r2_key TEXT NOT NULL,
// file_size INTEGER,
// captured_at TEXT NOT NULL
// );
// CREATE INDEX idx_captures_url ON captures(url);
D1 runs at the edge alongside your Worker. A query like "show me all screenshots of example.com" returns results in single-digit milliseconds because the database replica sits in the same datacenter as the Worker handling the request. For compliance monitoring workflows, this timestamped metadata becomes your audit trail.
Scheduled Captures with Cron Triggers
Cron Triggers run your Worker on a schedule without any external orchestrator. Define the schedule in wrangler.toml and deploy with wrangler deploy. Cloudflare invokes your Worker at the specified times automatically. The CPU time limit for Cron Triggers is 15 minutes (compared to 10ms free / 30s paid for HTTP-triggered Workers), which gives you plenty of room for batch operations.
// src/scheduled.ts
export interface Env {
SCREENSHOTRUN_API_KEY: string;
SCREENSHOTS: R2Bucket;
DB: D1Database;
}
const TARGETS = [
{ name: 'homepage', url: 'https://your-app.com' },
{ name: 'pricing', url: 'https://your-app.com/pricing' },
{ name: 'docs', url: 'https://your-app.com/docs' },
{ name: 'competitor', url: 'https://competitor.com' },
];
export default {
async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext) {
const date = new Date().toISOString().slice(0, 10);
for (const target of TARGETS) {
const params = new URLSearchParams({
url: target.url,
format: 'png',
width: '1920',
full_page: 'true',
block_ads: 'true',
block_cookies: 'true',
response_type: 'image',
});
const res = await fetch(
`https://api.screenshotrun.com/v1/screenshots/capture?${params}`,
{ headers: { Authorization: `Bearer ${env.SCREENSHOTRUN_API_KEY}` } }
);
if (!res.ok) continue;
const key = `daily/${date}/${target.name}.png`;
const blob = await res.arrayBuffer();
await env.SCREENSHOTS.put(key, blob, {
httpMetadata: { contentType: 'image/png' },
});
await env.DB.prepare(
'INSERT INTO captures (url, r2_key, file_size, captured_at) VALUES (?, ?, ?, ?)'
).bind(target.url, key, blob.byteLength, new Date().toISOString()).run();
}
},
};
Add the schedule to your config:
# wrangler.toml (append to existing config)
[triggers]
crons = ["0 8 * * *"] # Every day at 8:00 UTC
Every morning, the Worker captures each target, stores the PNG in R2 organized by date, writes metadata to D1. Over weeks and months, you build a visual archive of how pages evolve. Browse the R2 bucket through the Cloudflare dashboard, or build a simple frontend that queries D1 and renders the timeline. The brand monitoring use case covers the strategic side of competitor tracking.
Async Processing with Queues
Cloudflare Queues let you decouple the capture request from the capture execution. A producer Worker accepts the request and pushes a message to the queue. A consumer Worker picks up the message and processes the screenshot. This pattern handles burst traffic gracefully. A hundred simultaneous capture requests queue up and process at a controlled rate instead of hammering the API all at once.
// src/queue-producer.ts — accepts requests, pushes to queue
export interface Env {
SCREENSHOT_QUEUE: Queue;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const body: any = await request.json();
const urls: string[] = body.urls || [];
for (const url of urls) {
await env.SCREENSHOT_QUEUE.send({ url, requested_at: new Date().toISOString() });
}
return Response.json({ queued: urls.length });
},
};
// src/queue-consumer.ts — processes screenshots from queue
export interface Env {
SCREENSHOTRUN_API_KEY: string;
SCREENSHOTS: R2Bucket;
}
export default {
async queue(batch: MessageBatch, env: Env) {
for (const msg of batch.messages) {
const { url } = msg.body as { url: string };
const params = new URLSearchParams({
url,
format: 'webp',
width: '1280',
block_ads: 'true',
response_type: 'image',
});
const res = await fetch(
`https://api.screenshotrun.com/v1/screenshots/capture?${params}`,
{ headers: { Authorization: `Bearer ${env.SCREENSHOTRUN_API_KEY}` } }
);
if (res.ok) {
const hostname = new URL(url).hostname.replace(/\./g, '-');
await env.SCREENSHOTS.put(
`queue/${hostname}-${Date.now()}.webp`,
res.body,
{ httpMetadata: { contentType: 'image/webp' } }
);
msg.ack();
} else {
msg.retry();
}
}
},
};
Failed captures automatically retry with backoff (Queues handle this natively). The consumer processes messages in batches, so you can tune the concurrency to stay within your API rate limits. For bulk capture jobs like e-commerce listing captures or AI training dataset generation, Queues prevent your Worker from timing out on large URL lists.
Parameters for Workers Queries
Every parameter goes into the URL query string of your fetch() call. These are the ones most relevant for Workers-based workflows:
| Parameter | Value | What It Does |
|---|---|---|
url |
Any public URL | The page to capture. Pull from the request query string, Queue message body, KV lookup, or D1 query. |
format |
png, jpeg, webp, pdf | Output format. WebP produces files 3-5x smaller than PNG, which cuts R2 storage costs. |
width |
Integer (px) | Viewport width. 1280 for desktop, 390 for mobile. |
full_page |
true / false | Capture the entire scrollable page. See full page screenshots. |
block_ads |
true / false | Remove ads before capture. See ad blocking. |
block_cookies |
true / false | Dismiss cookie consent banners automatically. |
dark_mode |
true / false | Force dark mode rendering. See dark mode screenshots. |
response_type |
json / image | Return JSON metadata or raw image binary. Use image when storing to R2 directly. |
webhook_url |
URL | Receive results asynchronously. Useful for long captures that might approach timeout. See webhooks. |
cache_ttl |
Integer (seconds) | Cache identical requests API-side. Pairs well with KV caching for two-layer cache. |
stealth |
true / false | Bypass bot detection. See stealth mode. |
Bind these to wrangler.toml vars for defaults, override from request parameters for flexibility. For Cron Triggers, hardcode the parameters in the scheduled handler. For HTTP-triggered Workers, accept them as query string parameters and pass them through to the API.
What Teams Build with This Integration
OG image service at the edge. A SaaS platform generates Open Graph images for every user profile or content page. The Worker accepts a URL, captures it with specific viewport dimensions, stores the result in R2, returns the R2 public URL. Social platforms (Twitter, LinkedIn, Slack) fetch the OG image from R2, which sits behind Cloudflare's CDN. Latency is low because both the Worker and R2 serve from edge locations. The OG image generator guide covers the design patterns.
Visual monitoring on Cloudflare Pages deploy hooks. Cloudflare Pages fires a deploy_success webhook after each deployment. A Worker receives the webhook, captures key pages of the newly deployed site, compares screenshots against baselines stored in R2. If pixel differences exceed a threshold, the Worker posts to Slack or Discord. Developers catch layout regressions before users report them. The responsive design preview page walks through the visual QA workflow.
Compliance archival with R2 and D1. Regulated industries (financial services, healthcare, government) need timestamped proof of what a page displayed on a specific date. A Cron Trigger captures target pages daily. Screenshots go to R2 with versioning enabled. D1 stores the metadata. Auditors query by URL and date range through a simple dashboard Worker. R2's zero-egress pricing means serving hundreds of screenshots during an audit costs nothing extra.
Thumbnail API for user-submitted links. A content platform lets users submit links. A Worker captures each submitted URL, resizes the result to thumbnail dimensions with resize_width=400, stores it in R2, writes the R2 key back to D1 alongside the original link. The frontend displays thumbnails instantly from the CDN. Queues handle spikes when many users submit links simultaneously.
Competitor price tracking. An e-commerce team maintains a list of competitor product pages in D1. A weekly Cron Trigger reads the list, captures each page as a full-page PDF with prices visible, stores the PDFs in R2 organized by week. Pricing analysts compare PDFs across weeks to spot changes. The entire pipeline runs on Cloudflare's free or $5/month Workers plan plus R2 storage costs (pennies per GB).
ScreenshotRun fits naturally into the Workers ecosystem. Your Worker handles the workflow: when to capture, where to store, how to process the result, who to notify. The API handles the rendering. It loads pages, executes JavaScript, dismisses popups, produces the final image or PDF. One Worker, one API call, Cloudflare's storage and scheduling for everything else. Start with 200 free screenshots per month, scale up as your pipeline grows.
FAQ#
Yes. Call the ScreenshotRun API with a standard fetch() request from your Worker. The API handles all browser rendering on its own infrastructure. Your Worker only makes an HTTPS call, which works on both the free and paid Workers plans.
The network wait for the API response counts as wall time, not CPU time. A typical capture takes 2-5 seconds of wall time but only microseconds of CPU. You stay well within the 10ms free-plan CPU limit for HTTP-triggered Workers.
Add an R2 bucket binding in wrangler.toml, then use env.SCREENSHOTS.put(key, response.body) to store the image binary directly from the API response. R2 charges nothing for egress, so serving screenshots from R2 through Cloudflare's CDN has no bandwidth cost.
Use KV for caching screenshot URLs or small metadata with fast edge reads (under 10ms latency). Use R2 for storing the actual image files when you need a permanent archive. Many teams use both: KV as a fast lookup layer that points to R2 keys.
Yes. Cron Triggers let you run a Worker on a schedule defined in wrangler.toml. The scheduled handler gets a 15-minute CPU time limit instead of the usual 10-30ms, giving you room to capture multiple URLs in one invocation.
Use Cloudflare Queues. A producer Worker accepts the URL list and pushes each URL as a message to a queue. A consumer Worker processes messages one at a time with automatic retry on failure. This decouples the request from the processing and handles any batch size.