How Should You Handle Screenshot API Errors?
Classify Screenshotly API errors by status code, retry only what can succeed, and move slow or fragile captures to idempotent async jobs.
Most screenshot failures fall into one of two groups: problems a retry can fix and problems it can't. The fix is to classify every response by its status code, retry only the first group, and keep a record of the second.
This guide lists every status the Screenshotly capture endpoint returns, shows a retry loop we tested against a local mock of those responses, and explains when to stop retrying on the client and hand the job to the server. Rate-limit capacity planning has its own guide. This one is about recovering from failures.
For general background on backoff, see the AWS Builders' Library article on timeouts, retries and backoff with jitter and the Google SRE chapter on handling overload.
What a successful response looks like
POST https://screenshotly.app/api/screenshot returns one of two success shapes:
- Binary (default). Status 200 with the image or document in the body, and
Content-Typeset to the requested format (image/png,image/jpeg,image/webp,application/pdf,text/htmlorvideo/webm). The response also carriesX-Screenshot-Duration,X-Screenshot-Size,X-RateLimit-LimitandX-RateLimit-Remaining. - JSON (when
storage.enabledis true, Basic and above). Status 200 with{ "success": true, "url": "...", "format": "png", "size": 48213, "duration": 2140 }. Theurlis a signed download link.
Branch on Content-Type, not on the format you asked for. A client that always calls response.json() breaks on binary output, and a client that always reads bytes breaks on stored output.
Every error status, and what to do with it
Every error body is JSON with an error field. Most also include message.
| Status | error value |
Cause | Retry? |
|---|---|---|---|
| 400 | Invalid JSON |
The body isn't valid JSON | No. Fix the serializer |
| 400 | Invalid request data |
Schema validation failed. details lists the issues |
No. Fix the field |
| 400 | Unsafe URL |
Non-HTTP(S) scheme, credentials in the URL, a host that doesn't resolve, or a private/internal address | No |
| 400 | Invalid screenshot options |
selector matched nothing, or a cookie domain doesn't match the target URL |
Only after you change the request |
| 401 | Authentication failed |
API key missing or invalid | No |
| 403 | Authentication failed |
The account's email address isn't verified | No |
| 403 | Plan upgrade required |
A field needs a higher plan. minimumPlan names it |
No |
| 413 | Payload too large |
The body is over 64 KiB (maxBytes: 65536) |
No |
| 429 | Rate limit exceeded |
Per-minute limit or monthly quota reached. Sets Retry-After |
Only if the wait is short |
| 500 | Authentication failed |
The key lookup failed on the server | Yes, with backoff |
| 500 | Screenshot generation failed |
The browser couldn't finish the capture, for example a navigation timeout | Yes, with backoff |
| 503 | Capture proxy unavailable |
The regional proxy for proxyRegion isn't configured |
Yes, a few times. Then alert |
Some details that matter in practice:
- The schema is strict. Unknown keys are rejected with a 400. If you're migrating from another provider, a nested viewport object, a bare network-idle flag or a top-level webhook URL field will fail. Use top-level
width/height,waitForNetworkIdleandwebhook.urlinstead. There's no general resource-blocking field.blockAdscovers ads only: it blocks ad requests and hides common ad containers. The full field list is in the screenshot API reference. detailsis the useful part of a 400. It's a serialized list of validation issues with the offending path and key. Log it verbatim.- Plan errors are deterministic. A Free key requesting
"format": "pdf"always gets403with"minimumPlan": "basic". Surface that to whoever owns billing. Don't retry it. waitForSelectordoesn't fail. If the selector doesn't appear within 10 seconds, the capture continues without it.selector, which crops to an element, does fail: it returns 400 when nothing matches.- Target-page errors aren't API errors. The browser screenshots whatever it renders, so a 404 page on the target site comes back as a 200 image.
Which failures cost you anything
Two separate counters are involved, and retries affect them differently:
- The monthly quota counts only 2xx responses. A 500 or a 429 doesn't use a capture, so on quota terms retrying a failure is free.
- The per-minute request limit counts every request that passes validation. That includes requests that end in a 500 and requests rejected with a 429. Requests rejected earlier (401, a 400 from validation, a 403 plan error) never reach the limiter.
In practice, a retry loop with no delay can turn one 500 into a run of 429s. Always back off, and share the backoff across workers that use the same account. The rate limits guide covers a shared limiter.
A retry loop that honors Retry-After
This Node.js 18+ function retries 429, 500, 503 and network errors with exponential backoff and jitter. It uses Retry-After when the API sends one, and gives up early when the wait is long enough that it must be a monthly-quota 429.
const API_URL = 'https://screenshotly.app/api/screenshot';
const RETRYABLE = new Set([429, 500, 503]);
const MAX_WAIT_MS = 2 * 60 * 1000;
export class ScreenshotError extends Error {
constructor(status, body, retryable) {
super(`${status} ${body.error || 'Request failed'}: ${body.message || body.details || ''}`);
this.status = status;
this.body = body;
this.retryable = retryable;
}
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function backoff(attempt) {
const base = Math.min(30_000, 1000 * 2 ** (attempt - 1));
return base / 2 + Math.random() * (base / 2);
}
export async function capture(body, { attempts = 4, timeoutMs = 90_000 } = {}) {
for (let attempt = 1; ; attempt += 1) {
let response;
try {
response = await fetch(API_URL, {
method: 'POST',
headers: {
'x-api-key': process.env.SCREENSHOTLY_API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(timeoutMs),
});
} catch (error) {
// DNS, TLS, connection reset or our own timeout. After a timeout the
// server may still have finished (and counted) the capture.
if (attempt >= attempts) throw error;
await sleep(backoff(attempt));
continue;
}
if (response.ok) {
const type = response.headers.get('content-type') || '';
return type.includes('application/json')
? { stored: await response.json() }
: { bytes: Buffer.from(await response.arrayBuffer()), contentType: type };
}
const errorBody = await response.json().catch(() => ({}));
const retryable = RETRYABLE.has(response.status);
if (!retryable || attempt >= attempts) {
throw new ScreenshotError(response.status, errorBody, retryable);
}
const retryAfter = Number(response.headers.get('retry-after'));
const waitMs = response.status === 429 && retryAfter > 0 ? retryAfter * 1000 : backoff(attempt);
// A monthly-quota 429 can ask you to wait until next month. Stop and alert instead.
if (waitMs > MAX_WAIT_MS) throw new ScreenshotError(response.status, errorBody, false);
await sleep(waitMs);
}
}
Usage:
try {
const result = await capture({ url: 'https://example.com', fullPage: true });
// result.bytes + result.contentType, or result.stored.url when storage is enabled
} catch (error) {
if (error.status === 403 && error.body.minimumPlan) notifyBilling(error.body);
else if (error.status === 400) logInvalidRequest(error.body);
else throw error;
}
Why it's built this way:
- Set your own client timeout. How long the server keeps a synchronous request open depends on where it runs, so don't assume a fixed limit. 90 seconds is a reasonable ceiling. A timeout doesn't prove the capture failed: the server may have completed it and counted it after your client gave up. If a URL times out more than once, move it to async jobs, where an
Idempotency-Keymakes resending safe. - Full jitter on half the base delay keeps a burst of failed workers from retrying in lockstep.
MAX_WAIT_MSseparates the two kinds of 429. A per-minute 429 asks for 60 seconds at most. A quota 429 asks you to wait until the quota resets, and sleeping that long inside a request handler only hides the problem.- Errors thrown with
retryable: falseshould go to an alert or a dead-letter list, not back into the queue.
We checked this function against a local mock server that replays the real response shapes: binary 200, stored-JSON 200, a 429 with Retry-After: 1, a quota 429, a 500 followed by success, a 403 plan error and a 400 validation error. The throttled and flaky cases succeeded on the second call. The quota, 403 and 400 cases threw after one call without retrying.
When to stop retrying on the client: async jobs
Client-side retries have a weak point. If the connection drops after the server has started a capture, you can't tell whether to try again. For slow captures (heavy full-page pages, PDFs, waitForNetworkIdle on chatty sites, WebM recordings) or work you can't afford to lose, queue a job instead. POST /api/jobs takes the same body as the synchronous endpoint and needs the Basic plan or higher. See async screenshots for when to choose each mode.
const ORIGIN = 'https://screenshotly.app';
const headers = {
'x-api-key': process.env.SCREENSHOTLY_API_KEY,
'Content-Type': 'application/json',
};
export async function captureAsync(body, idempotencyKey) {
const queued = await fetch(`${ORIGIN}/api/jobs`, {
method: 'POST',
headers: { ...headers, 'Idempotency-Key': idempotencyKey },
body: JSON.stringify(body),
});
if (!queued.ok) throw new Error(`Queue failed: ${queued.status} ${JSON.stringify(await queued.json())}`);
const { id, statusUrl } = await queued.json(); // 202 new, 200 replayed
for (;;) {
await new Promise((resolve) => setTimeout(resolve, 3000));
const job = await (await fetch(`${ORIGIN}${statusUrl}`, { headers })).json();
if (job.status === 'SUCCEEDED') return job.resultUrl; // signed, short-lived
if (job.status === 'FAILED') throw new Error(`Job ${id} failed: ${job.errorCode} ${job.errorMessage}`);
if (job.status === 'CANCELED') throw new Error(`Job ${id} was canceled`);
// QUEUED or RUNNING. errorCode CAPTURE_RETRY means the worker will try again.
}
}
How the job contract handles failures:
- Idempotency. Reusing an
Idempotency-Keywithin a workspace returns the original job with"replayed": trueand status 200 instead of 202. That makes it safe to resend the queue request after a timeout. Keys can be up to 200 printable ASCII characters. Anything else returns400 Invalid Idempotency-Key. Base the key on your own record ID (invoice-42), not on a random value generated per attempt. - Server-side retries. A failed capture goes back to
QUEUEDwitherrorCode: "CAPTURE_RETRY"and is retried after at least about 5 seconds, then at least about 15 seconds (worker scheduling adds time), for up to 3 attempts in total. CompareattemptswithmaxAttemptsin the job response. - Terminal failures.
FAILEDcomes witherrorCodeset toCAPTURE_FAILED(every attempt failed) orWORKER_TIMEOUT(the worker stopped responding on the last attempt). Neither uses quota, because only successful captures count. - Results expire.
resultUrlis valid for 15 minutes. Read the job again to get a fresh link while the result is still within your retention period (1 to 30 days). - Cancellation.
DELETE /api/jobs/{id}cancels a queued job immediately. A running job may finish its current browser step before the worker discards the output.404means the job isn't queued or running in your workspace. - Async-only errors. Free keys get
403 Plan upgrade required(minimumPlan: "basic"). Playground keys get403 Async captures require an account API key. An unknown job ID returns404 Job not found.
Both client loops above were checked against a mock job server. A repeated Idempotency-Key produced one job, a CAPTURE_RETRY → RUNNING → SUCCEEDED sequence returned the result URL, and a terminal CAPTURE_FAILED threw with the error code.
If you don't want to poll, add a webhook object to the job body and Screenshotly will POST the result to you. The webhooks guide covers signature checks and delivery retries. For bulk work, the Growth plan adds POST /api/jobs/batch with up to 20 captures per call. See the batch processing guide. The full job contract is in the async jobs reference.
Degrade gracefully when a capture fails
Retries reduce failures but won't eliminate them. Decide in advance what users see when a capture fails:
- Serve the last good image. If you already store captures, keep the previous version until the new one succeeds. Caching on your side also cuts the number of requests that can fail. See the caching guide.
- Show a placeholder for thumbnails and previews, and queue a later retry as an async job.
- Fail loudly for documents. For invoices, reports and compliance archives, a missing PDF should raise an alert, not quietly fall back to something else.
What to log for every failure
Record enough to answer the question "is this my request, my plan, my volume or the service?":
- the HTTP status, plus
error,messageanddetailsfrom the body minimumPlanon 403sRetry-After,X-RateLimit-LimitandX-RateLimit-Remainingon 429s- the target URL and the request fields (never the API key)
- the attempt number, and for async work the job
id,attemptsanderrorCode
A rise in 400s means a bad deploy on your side. A rise in 429s is a pacing problem. A rise in 500s for one domain usually means that site is slow or blocking automation, so send it to async jobs or try waitForNetworkIdle or delay. A rise in 500s across every domain is worth reporting to support.
Summary
- Branch success handling on
Content-Type: binary by default, JSON when storage is enabled. - Retry 429 (short waits only), 500, 503 and network errors with jittered backoff. Never retry 400, 401, 403 or 413.
- Failures don't use quota, but they do count toward the per-minute limit.
- Move slow or critical captures to
POST /api/jobswith anIdempotency-Key, and let the server handle retries.
Plan details and quotas are on the pricing page.
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
Which Screenshotly errors should I retry?
Retry 429 after the Retry-After delay when that delay is short, 500 (capture failed), 503 (capture proxy unavailable) and network errors or client timeouts. Don't retry 400, 401, 403 or 413: the same request will fail the same way until you change the body, the key or the plan.
Do failed requests count against my monthly quota?
No. Only 2xx responses count toward the monthly capture quota. Every request that passes validation still counts toward your per-minute request limit, though, including requests that later fail, so an aggressive retry loop can turn a 500 into a 429.
What happens if the page I'm capturing returns a 404?
The API captures whatever the browser renders, so a target page's 404 or 500 error page comes back as a normal 200 screenshot. If that matters, check the target URL yourself before capturing, or inspect the image. Screenshotly only returns 404 from the async job endpoints, when a job ID doesn't exist in your workspace.
How do I tell a per-minute 429 from a monthly-quota 429?
Look at Retry-After and the message. A per-minute 429 has a Retry-After of at most 60 seconds and the message 'Request rate limit exceeded'. A quota 429 says 'Rate limit exceeded. Limit resets at <ISO date>', sets X-RateLimit-Limit to 0, and its Retry-After runs until the next UTC month on paid plans. Free quotas never reset, so you have to upgrade.
When should I switch from the synchronous endpoint to async jobs?
Switch when captures are slow enough to risk a client or hosting-platform timeout (heavy full-page captures, PDFs, waitForNetworkIdle on busy pages, WebM recordings), or when you can't afford to lose a request to a dropped connection. POST /api/jobs (Basic plan and above) accepts the same body, deduplicates with an Idempotency-Key header and retries failed captures on the server up to three times.
Ready to capture your first screenshot?
Get started with 100 free screenshots. No credit card required.