Migrating from Puppeteer to a Screenshot API
A hands-on guide to moving capture code from Puppeteer or Playwright to the Screenshotly API. It includes a field-by-field conversion table, what has no equivalent, shadow-mode comparison, percentage rollout, and the gotchas that surface mid-migration.
You have a working Puppeteer or Playwright capture service and you have decided to move the capture-only parts to a screenshot API. This guide covers the how: converting options, running both backends in parallel, rolling out safely, and turning the old fleet off.
If you are still deciding whether to switch, start with the build-vs-buy comparison. It covers cost inputs and the cases where self-hosting is the better choice.
All examples call POST https://screenshotly.app/api/screenshot with an x-api-key header. The request schema is strict, so unknown fields are rejected with a 400 instead of being silently ignored. That is useful during migration because typos surface immediately.
Before You Start: Inventory Your Capture Code
Find every call site first:
grep -rn "page.screenshot\|\.screenshot(\|page.pdf\|page.screencast" src/
Sort each call into one of three buckets:
- Capture-only. Navigate to a public URL, maybe wait, then capture. These migrate directly.
- Capture with light setup. Cookies, headers, a dark-mode toggle, a CSS hide, or a small script before capture. These usually migrate, but some fields need a paid plan (see the mapping table).
- Capture at the end of a workflow. Login forms, clicks, multi-page navigation, or URLs on a private network. These stay on Puppeteer or Playwright. The API takes one public URL per request and cannot drive a session.
Migrate bucket 1 first.
Step 1: Put Both Backends Behind One Function
A thin wrapper lets you switch backends with configuration and compare their output.
// screenshot-service.js
import puppeteer from 'puppeteer';
export async function captureScreenshot(url, options = {}) {
if (process.env.SCREENSHOT_BACKEND === 'api') {
return captureViaApi(url, options);
}
return captureViaPuppeteer(url, options);
}
async function captureViaPuppeteer(url, options) {
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
await page.setViewport({
width: options.width ?? 1920,
height: options.height ?? 1080,
deviceScaleFactor: options.deviceScaleFactor ?? 1,
});
await page.goto(url, {
waitUntil: options.waitForNetworkIdle ? 'networkidle0' : 'domcontentloaded',
timeout: 30_000,
});
if (options.delay) await new Promise((r) => setTimeout(r, options.delay));
return Buffer.from(await page.screenshot({
type: options.format ?? 'png',
fullPage: options.fullPage ?? false,
}));
} finally {
await browser.close();
}
}
async function captureViaApi(url, options) {
const response = await fetch('https://screenshotly.app/api/screenshot', {
method: 'POST',
headers: {
'x-api-key': process.env.SCREENSHOTLY_API_KEY,
'content-type': 'application/json',
},
body: JSON.stringify(toApiRequest(url, options)),
});
if (!response.ok) {
const error = await response.json().catch(() => ({}));
throw new Error(`Screenshotly ${response.status}: ${error.message ?? error.error ?? 'request failed'}`);
}
return Buffer.from(await response.arrayBuffer());
}
function toApiRequest(url, options) {
const request = {
url,
format: options.format ?? 'png',
fullPage: options.fullPage ?? false,
};
// width and height are only applied when both are present.
if (options.width && options.height) {
request.width = options.width;
request.height = options.height;
}
if (options.deviceScaleFactor) request.deviceScaleFactor = options.deviceScaleFactor; // 1–3
if (options.waitForNetworkIdle) request.waitForNetworkIdle = true;
if (options.delay) request.delay = Math.min(options.delay, 10_000); // milliseconds
return request;
}
The wrapper keeps the same option names on both sides, so the mapping lives in one function. delay is in milliseconds on both backends.
Step 2: Option-by-Option Conversion
Basic viewport capture
Puppeteer
await page.setViewport({ width: 1280, height: 800 });
await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
const buffer = await page.screenshot({ type: 'png' });
Playwright
await page.setViewportSize({ width: 1280, height: 800 });
await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
const buffer = await page.screenshot({ type: 'png' });
Screenshotly
{
"url": "https://example.com",
"width": 1280,
"height": 800,
"format": "png"
}
width (320–3840) and height (240–3840) are top-level fields. If you send only one of them, the default 1920×1080 viewport is used. If you also send device, the device preset takes precedence.
Full-page capture
Puppeteer and Playwright: page.screenshot({ fullPage: true }). Screenshotly: "fullPage": true.
Waiting for content
| Puppeteer / Playwright | Screenshotly |
|---|---|
waitUntil: 'domcontentloaded' |
Default behaviour |
Puppeteer waitUntil: 'networkidle0' / Playwright 'networkidle' |
"waitForNetworkIdle": true (navigates with networkidle0) |
waitUntil: 'load' or Puppeteer 'networkidle2' |
No equivalent. Use waitForSelector or delay |
page.waitForSelector('.chart') |
"waitForSelector": ".chart". Waits up to 10 s, then captures anyway |
await new Promise(r => setTimeout(r, 2000)) |
"delay": 2000 (milliseconds, max 10,000) |
goto(url, { timeout }) |
Fixed 30 s navigation timeout, not configurable |
Puppeteer's old page.waitForTimeout() was removed in v22, so legacy code may still use it. In the API it maps to delay.
Because waitForSelector doesn't fail when the element is missing, a page that never renders your target produces a capture of whatever did render. If your Puppeteer code relied on waitForSelector throwing, add a check on the output (for example, image dimensions or a visual diff) during shadow mode.
Mobile viewport
Puppeteer
import puppeteer, { KnownDevices } from 'puppeteer';
await page.emulate(KnownDevices['iPhone 13']);
Playwright
import { devices } from 'playwright';
const context = await browser.newContext({ ...devices['iPhone 13'] });
Screenshotly
{
"url": "https://example.com",
"device": "mobile",
"deviceScaleFactor": 3,
"userAgent": "<the mobile user-agent string your site expects>"
}
This is a partial equivalent. The presets (desktop 1920×1080, laptop 1366×768, tablet 768×1024, mobile 375×812) set the viewport only. They don't enable touch events or isMobile, and they don't change the user agent. Sites that serve different markup based on user agent need an explicit userAgent. Sites that branch on touch support may still render their desktop layout, so check them in shadow mode.
Element screenshot
Puppeteer: const el = await page.$('.hero'); await el.screenshot();
Playwright: await page.locator('.hero').screenshot();
Screenshotly: "selector": ".hero". If no element matches, the API returns 400 Invalid screenshot options instead of an image. For a fixed rectangle, use "clip": { "x": 0, "y": 0, "width": 1200, "height": 630 }.
Puppeteer
const pdf = await page.pdf({ format: 'A4', printBackground: true });
Screenshotly (Basic plan or higher)
{ "url": "https://example.com/invoice/123", "format": "pdf" }
The API always produces A4 with 1 cm margins and backgrounds printed. It has no options for paper size, landscape, margins, scale, header/footer templates or page ranges. If your page.pdf() call sets any of those, keep that path on Puppeteer or accept A4.
Everything else
| Puppeteer | Playwright | Screenshotly field | Plan |
|---|---|---|---|
page.screenshot({ type: 'jpeg', quality }) |
same | format: 'jpeg', quality |
All |
type: 'webp' |
same | format: 'webp' |
All |
page.screenshot({ clip }) |
same | clip |
All |
setViewport({ deviceScaleFactor }) |
context deviceScaleFactor |
deviceScaleFactor (1–3) |
All |
page.setUserAgent() |
context userAgent |
userAgent |
All |
page.emulateMediaFeatures([{ name: 'prefers-color-scheme', value: 'dark' }]) |
page.emulateMedia({ colorScheme: 'dark' }) |
darkMode: true |
All |
page.emulateTimezone() |
context timezoneId |
timezone |
All |
| Request interception to drop ad requests | page.route() |
blockAds: true |
All |
page.content() |
same | format: 'html' |
Basic+ |
page.setExtraHTTPHeaders() |
same | headers |
Basic+ |
browser.setCookie() / page.setCookie() |
context.addCookies() |
cookies |
Basic+ |
page.setGeolocation() |
context geolocation |
geolocation |
Growth+ |
page.evaluate(script) |
same | javascript (≤ 5,000 chars) |
Growth+ |
page.addStyleTag({ content: '.x{display:none}' }) |
same | hideSelectors: ['.x'] |
Growth+ |
page.screencast() |
video recording | format: 'webm', videoDuration 1–15 s |
Scale |
screenshot({ omitBackground: true }) |
same | No equivalent | — |
page.authenticate() (HTTP Basic) |
context httpCredentials |
No dedicated field (see below) | — |
page.click(), page.type(), multi-page flows |
same | No equivalent | — |
puppeteer.launch({ args }), extensions |
same | No equivalent | — |
If a request uses a field above your plan, the API returns 403 with a minimumPlan value. It does not silently drop the field.
Step 3: Shadow Mode
Keep serving Puppeteer output, call the API for a sample, and compare the two.
const SHADOW_SAMPLE = Number(process.env.SHADOW_SAMPLE ?? '0'); // e.g. 0.05 for 5%
export async function captureScreenshot(url, options = {}) {
const primary = await captureViaPuppeteer(url, options);
if (Math.random() < SHADOW_SAMPLE) {
captureViaApi(url, options)
.then((shadow) => compareOutputs(url, primary, shadow))
.catch((error) => logShadowError(url, error));
}
return primary;
}
What compareOutputs should record:
- Dimensions. A mismatch usually means a viewport or
fullPagemapping error. - A perceptual diff (pixelmatch or a similar tool), not byte equality. PNG encoders differ, so identical-looking images rarely match byte for byte.
- Failures by status code on the API side:
400mapping bugs,403plan gates,429quota or rate limit,500render failures.
Shadow captures count against quota when they succeed. Size the sample to your plan, or use a fixed list of representative URLs instead of live traffic.
Step 4: Gradual Rollout
Route a stable slice of traffic to the API, keyed on something deterministic so the same URL always takes the same path:
import { createHash } from 'node:crypto';
function bucket(key) {
return createHash('sha256').update(key).digest().readUInt16BE(0) / 0xffff;
}
export async function captureScreenshot(url, options = {}) {
const share = Number(process.env.API_TRAFFIC_SHARE ?? '0'); // 0 → 1
return bucket(url) < share
? captureViaApi(url, options)
: captureViaPuppeteer(url, options);
}
Increase API_TRAFFIC_SHARE in steps. Before each step, check that the API path's error rate and visual diffs are acceptable for your use case. Keep the Puppeteer path deployable until you have run at 100% for long enough to trust it.
Step 5: Edge Cases That Surface Mid-Migration
Rate limits and quota
Each plan has a requests-per-minute limit (5 on Free, 40 on Basic, 80 on Growth, 200 on Scale) and a capture quota. Both return 429 with a Retry-After header. Successful responses include X-RateLimit-Remaining. A cron job that used to fan out 500 Puppeteer tabs at once needs a concurrency limit and must honour Retry-After:
async function captureWithRetry(url, options, attempts = 3) {
for (let i = 0; i < attempts; i++) {
const response = await fetch('https://screenshotly.app/api/screenshot', {
method: 'POST',
headers: { 'x-api-key': process.env.SCREENSHOTLY_API_KEY, 'content-type': 'application/json' },
body: JSON.stringify(toApiRequest(url, options)),
});
if (response.status !== 429 && response.status < 500) {
if (!response.ok) throw new Error(`Screenshotly ${response.status}`);
return Buffer.from(await response.arrayBuffer());
}
const wait = Number(response.headers.get('retry-after') ?? 2 ** i);
await new Promise((r) => setTimeout(r, wait * 1000));
}
throw new Error(`Gave up on ${url}`);
}
The quota resets monthly on paid plans, so a quota 429 can carry a long Retry-After. Cap the wait and fail the job instead of sleeping for days.
Long-running or bulk work: use jobs instead of loops
If your Puppeteer service was really a queue worker, use the API's durable jobs instead of rebuilding the queue on top of synchronous calls:
POST /api/jobs(Basic+) accepts the same body, returns202with a status URL, and makes up to 3 attempts per capture. Send anIdempotency-Keyheader so client retries don't create duplicate jobs.POST /api/jobs/batch(Growth+) accepts{ "captures": [...] }with up to 20 captures per request.
See Async and batch jobs for status values and result retention.
Cookies and headers for logged-in pages
{
"url": "https://app.example.com/reports/42",
"cookies": [
{ "name": "session_id", "value": "<session value>", "domain": "app.example.com", "secure": true, "httpOnly": true }
]
}
Cookies must belong to the target URL's domain. A cookie for another domain is rejected. Don't hard-code real session values, and use short-lived sessions created for capture.
Custom headers are sent with every request the page makes, including third-party scripts and images, because they work like Puppeteer's setExtraHTTPHeaders(). Don't put long-lived bearer tokens there if the page loads third-party resources. Prefer a domain-scoped cookie.
There is no authentication field. URLs that embed credentials (https://user:pass@host) are rejected. If you used page.authenticate() for HTTP Basic auth, you can send an Authorization: Basic … header through headers, with the same third-party caveat.
Private, localhost and staging URLs
The API rejects URLs that resolve to private or reserved addresses: localhost, *.local, *.internal, RFC 1918 ranges, link-local, carrier-grade NAT and similar. It also blocks any subresource the page requests from those ranges. Staging behind a VPN, intranet dashboards and http://localhost:3000 previews must stay on your self-hosted browser.
Rendering differences to expect
- Video, audio and WebSocket requests are not loaded. Pages whose content arrives over a WebSocket, or whose hero is a video, will look different from your Puppeteer output.
- Web fonts in viewport captures. At the time of writing, the renderer skips web-font downloads for non-full-page captures, so text can fall back to system fonts. Full-page captures load web fonts. If typography matters, compare both modes in shadow mode before you switch.
- Custom JavaScript errors don't fail the capture. A
javascriptsnippet that throws is logged, and the capture proceeds. Verify the effect in the output, not just the status code.
Binary vs JSON responses
By default the API returns the image or PDF bytes, with the right Content-Type. If you send "storage": { "enabled": true } (Basic+), it returns JSON instead: { "success": true, "url": "...", "format": "png", "size": ..., "duration": ... }. Branch on Content-Type if both shapes can occur.
Step 6: Test the Mapping
- Unit test
toApiRequest. Assert the exact JSON for each option combination you use. The strict schema means an extra key fails in production, so catch it in CI. - Contract test against a mock. Stub
fetch(or point the client at a local mock server) and test your handling of200binary,400,403,429withRetry-After, and500. - Visual check on real URLs. Capture your most important pages with both backends and review the diffs before raising the traffic share.
Decommission Checklist
- All bucket-1 and bucket-2 call sites go through the API path
- Remaining Puppeteer call sites are deliberate (interaction, private network, custom PDF) and documented
- Error rate and visual diffs on the API path are acceptable at 100% traffic
- Retry and concurrency limits respect
429andRetry-After - Monthly volume fits the plan quota with headroom (only successful captures count)
- Unused
puppeteer/playwrightdependencies, Chrome layers and Dockerfiles removed - Worker services, queues and alarms that only served capture are shut down
- The API key is in your secret manager and has been rotated since testing
Summary
Migrating capture code is mostly an implementation swap behind one function. Map options field by field. Keep anything that needs interaction, private-network access or custom PDF layout on Puppeteer. Run shadow mode on a sample, roll out by deterministic bucket, and decommission only what the API has fully replaced.
Test your own URLs in the playground, or create a free account. It includes 100 captures, enough to run the mapping against your most important pages. The full request reference is in the API docs.
About the Author

Asad Ali
CTO at ZTABS and the developer behind Screenshotly. Writes about screenshot automation, API design, and building reliable SaaS backends with Next.js, Node.js, and TypeScript.
Credentials: CTO at ZTABS, full-stack developer, builder and maintainer of Screenshotly and its official JavaScript and Python clients
Frequently Asked Questions
Can I run Puppeteer and the API side by side during migration?
Yes. Put both behind one capture function, run the API in shadow mode on a sample of traffic, then shift traffic gradually. Workloads that need clicks, form filling, or private-network URLs can stay on Puppeteer indefinitely. Split by workload, not by date.
Which Puppeteer options have no direct equivalent in the Screenshotly API?
Multi-step interaction (click, type, navigation chains), the 'load' and 'networkidle2' wait events, a configurable navigation timeout (it is fixed at 30 seconds), custom PDF paper sizes and margins (PDF is A4 with 1 cm margins), omitBackground, browser launch flags, and full mobile device emulation. The 'mobile' preset sets a 375×812 viewport, but it does not switch to a mobile user agent or touch mode.
Does shadow mode use up my quota?
Yes. Every successful shadow capture counts as a capture, so mirroring all production traffic doubles your capture volume for that period. Sample a fixed set of URLs, or a small percentage of traffic, and make sure the plan quota covers it. Failed captures do not count.
Ready to capture your first screenshot?
Get started with 100 free screenshots. No credit card required.