Tutorial

Screenshot Webhooks: Signed Callbacks for Async Captures

Attach a webhook to a capture, verify the X-Screenshotly-Signature header, survive retries, and fall back to polling when a delivery never arrives.

Asad AliNovember 15, 202510 min read

A synchronous call to POST /api/screenshot holds the connection open until the browser finishes. That is fine for one quick capture. It is not fine for a heavy full-page PDF, a long waitForSelector, or a few hundred captures fanned out from a queue. For those, Screenshotly lets you attach a webhook: you submit the capture, return immediately, and receive a signed HTTP callback when it completes or fails.

This guide covers what Screenshotly actually sends, how to verify it, how retries behave, and what to do when a callback never arrives. Everything here is based on the current API contract: the async jobs reference and the screenshot request reference. A dedicated docs guide for webhooks is planned at docs.screenshotly.app/guides/webhooks. For deciding when async capture is the right tool, see async screenshots.

When to use a webhook

Webhooks are delivery notifications. They don't make a capture faster; they stop your code from waiting on it.

Situation Use
One capture that usually finishes in a few seconds, and the caller needs the bytes now Synchronous POST /api/screenshot, no webhook
A slow or unreliable page, a PDF, or anything long enough to risk a client or platform request timeout POST /api/jobs + webhook
Many captures triggered at once (reports, catalog refreshes) POST /api/jobs or POST /api/jobs/batch (Growth+, up to 20) + webhook
You can't expose a public HTTPS endpoint POST /api/jobs + polling GET /api/jobs/{id}

Webhook delivery requires the Basic plan or higher. So do async jobs. Batch jobs require Growth or higher. Current plans and limits are on the pricing page.

Attaching a webhook to a capture

There is no separate webhook registration endpoint for captures. You add a webhook object to the capture request body. The same body works on POST /api/screenshot and POST /api/jobs.

{
  "url": "https://example.com/pricing",
  "format": "png",
  "fullPage": true,
  "webhook": {
    "url": "https://app.example.com/hooks/screenshotly?ref=report-8421",
    "secret": "whsec_replace_me",
    "headers": { "X-Report-Id": "report-8421" }
  }
}

The webhook fields:

Field Type Notes
url string, URL, max 2048 chars Must be a public http or https URL. URLs with credentials, private IP ranges and internal hostnames are rejected as Unsafe URL (400).
method "POST" or "PUT" Defaults to POST.
headers object of strings Optional extra headers sent with every delivery. Up to 50; hop-by-hop and forwarding headers such as Host, Content-Length and X-Forwarded-For are not allowed.
secret string, max 4096 chars Enables the HMAC signature. Strongly recommended.

The request schema is strict. A top-level webhook URL field, as some other APIs use, is rejected with 400 Invalid request data; the URL belongs in webhook.url.

Submitting it as an async job:

curl -i -X POST https://screenshotly.app/api/jobs \
  -H "x-api-key: $SCREENSHOTLY_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: report-8421-pricing" \
  -d '{
    "url": "https://example.com/pricing",
    "format": "png",
    "fullPage": true,
    "webhook": {
      "url": "https://app.example.com/hooks/screenshotly?ref=report-8421",
      "secret": "whsec_replace_me"
    }
  }'

A new job returns 202 Accepted with a Location header and a body like:

{ "id": "<job id>", "status": "QUEUED", "replayed": false, "statusUrl": "/api/jobs/<job id>" }

Store the job id next to your own reference (report-8421 above). You'll need it for the polling fallback. If you retry the same request with the same Idempotency-Key, you get the original job back with 200 and "replayed": true, not a second capture.

Local development: because localhost and private addresses are rejected, point webhook.url at a public tunnel to your machine, or poll the job instead.

What Screenshotly sends

Capture webhooks have two event types.

screenshot.completed is sent after a successful capture:

{
  "event": "screenshot.completed",
  "timestamp": "2026-11-13T09:41:07.512Z",
  "data": {
    "url": "https://example.com/pricing",
    "format": "png",
    "size": 482113,
    "storageUrl": "https://screenshotly.app/api/assets/<asset id>?expires=<unix seconds>&signature=<signature>",
    "duration": 6120
  }
}

size is in bytes and duration in milliseconds. storageUrl is a signed download link valid for 24 hours, and never longer than your account's result retention (1–30 days, 7 by default). Fetching it may answer with a 307 redirect to a short-lived object-storage URL, so follow redirects and download promptly rather than storing the link.

screenshot.failed is sent only by async jobs, and only after the job has used all of its capture attempts:

{
  "event": "screenshot.failed",
  "timestamp": "2026-11-13T09:44:52.006Z",
  "data": {
    "url": "https://example.com/pricing",
    "format": "png",
    "error": "The capture could not be completed"
  }
}

The error string is deliberately generic. Read GET /api/jobs/{id} for the job's errorCode (for example CAPTURE_FAILED or WORKER_TIMEOUT) and errorMessage.

Sync requests vs jobs

A webhook on the synchronous endpoint behaves differently:

  • It fires only on success. If a synchronous capture fails, you get the error in the HTTP response and no webhook is sent.
  • storageUrl is present only if you also set "storage": { "enabled": true } (Basic+). Without storage, the image bytes are in the HTTP response and the webhook is just a notification.

For most webhook use cases, use POST /api/jobs. It always stores the result, retries the capture, and sends screenshot.failed when it gives up.

Delivery headers

Every delivery includes:

Header Value
Content-Type application/json
User-Agent Screenshotly-Webhook/1.0
X-Screenshotly-Timestamp The same ISO 8601 value as the body's timestamp
X-Screenshotly-Signature sha256=<hex HMAC>. Present only when webhook.secret is set.

Plus any headers you supplied in webhook.headers.

What the payload doesn't contain

There is no job ID and no event ID in the body. Correlate deliveries with your own reference, either as a query parameter on webhook.url or a custom header in webhook.headers. Both are sent unchanged on every attempt.

Verifying the signature

When webhook.secret is set, Screenshotly computes HMAC-SHA256(secret, rawBody) and sends it as lowercase hex after a sha256= prefix. Two details matter:

  1. Sign the raw bytes. Compute the HMAC over the body exactly as received. If you parse JSON and re-serialize it, key order or whitespace can change and the signature won't match.
  2. The timestamp header is not signed on its own. Only the body is signed. The body contains the same timestamp, so check freshness against the body value after the signature passes.

Node.js (Express)

import crypto from 'node:crypto';
import express from 'express';

const app = express();
const SECRET = process.env.SCREENSHOTLY_WEBHOOK_SECRET;
const MAX_AGE_MS = 15 * 60 * 1000;

function isValidSignature(rawBody, header) {
  if (!header || !header.startsWith('sha256=')) return false;
  const expected = crypto.createHmac('sha256', SECRET).update(rawBody).digest('hex');
  const received = header.slice('sha256='.length);
  if (received.length !== expected.length) return false;
  return crypto.timingSafeEqual(Buffer.from(received, 'utf8'), Buffer.from(expected, 'utf8'));
}

app.post('/hooks/screenshotly', express.raw({ type: 'application/json' }), async (req, res) => {
  if (!isValidSignature(req.body, req.get('x-screenshotly-signature'))) {
    return res.status(401).end();
  }

  const event = JSON.parse(req.body.toString('utf8'));
  if (Math.abs(Date.now() - Date.parse(event.timestamp)) > MAX_AGE_MS) {
    return res.status(400).end();
  }

  // Record the event and acknowledge quickly; do the heavy work elsewhere.
  const signature = req.get('x-screenshotly-signature');
  await enqueueScreenshotEvent({ ref: req.query.ref, event, signature });
  res.status(204).end();
});

express.raw keeps req.body as a Buffer, so the HMAC sees the original bytes. The freshness window is your choice. Retries resend the original timestamp, so make the window comfortably longer than the retry span (a few minutes) or you'll reject legitimate retries. Fifteen minutes leaves room for clock skew and slow workers.

Python (Flask)

import hashlib
import hmac
import json
import os
from datetime import datetime, timezone

from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["SCREENSHOTLY_WEBHOOK_SECRET"].encode()
MAX_AGE_SECONDS = 15 * 60


@app.post("/hooks/screenshotly")
def screenshotly_webhook():
    raw = request.get_data()
    header = request.headers.get("X-Screenshotly-Signature", "")
    expected = "sha256=" + hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(header, expected):
        abort(401)

    event = json.loads(raw)
    sent = datetime.fromisoformat(event["timestamp"].replace("Z", "+00:00"))
    if abs((datetime.now(timezone.utc) - sent).total_seconds()) > MAX_AGE_SECONDS:
        abort(400)

    enqueue_screenshot_event(ref=request.args.get("ref"), event=event)
    return "", 204

Use request.get_data() before touching request.json, and compare with hmac.compare_digest, not ==.

Treat the secret like an API key: keep it in your secret store, never in client-side code, and rotate it by sending a new webhook.secret on new captures. Jobs already queued keep the secret they were submitted with.

How delivery and retries work

Webhook deliveries go into a separate durable queue in Screenshotly's database. A slow or failing endpoint doesn't block captures, and a worker restart doesn't lose a pending delivery.

Rule Behavior
Success Any 2xx response within 10 seconds
Failure Non-2xx status, timeout, connection error, or any redirect (redirects are not followed)
Attempts Up to 5 per delivery
Backoff At least 5 s, 15 s, 45 s, then 135 s between attempts (worker scheduling can add time)
Final state DELIVERED or FAILED, visible on the job

Some consequences for your receiver:

  • Acknowledge fast. Verify, persist, return 2xx. Download the image and run your processing from your own queue, not inside the request. A handler that takes more than 10 seconds counts as failed and is retried.
  • Expect duplicates. Delivery is at-least-once. Your handler could commit work and then time out before Screenshotly sees the 2xx. Every retry resends the same payload, byte for byte, so the same signature means the same delivery. Dedupe on the signature (or a SHA-256 of the raw body) plus your own reference.
  • Don't redirect. If your endpoint moved, update webhook.url on new requests. A 301 or 308 from the old URL is a failed attempt, not a forward.
  • Five attempts is a short window. The scheduled gaps add up to about three and a half minutes. A deploy or an outage longer than that will leave deliveries in FAILED. That's why you need a fallback.

A minimal idempotent consumer:

async function enqueueScreenshotEvent({ ref, event, signature }) {
  // Unique index on (ref, signature) turns retries into no-ops.
  const inserted = await db.webhookEvents.insertIfAbsent({ ref, signature, event });
  if (!inserted) return;
  await queue.publish('screenshot-events', { ref, event });
}

This is the function the Express handler above calls. Then download from storageUrl in the worker that consumes screenshot-events, and upload to your own storage if you need the file for longer than your retention period.

Polling as a fallback

Every async job can be read directly, so webhooks and polling work together. Use the webhook for speed and polling to reconcile:

curl https://screenshotly.app/api/jobs/<job id> \
  -H "x-api-key: $SCREENSHOTLY_API_KEY"

The response includes status (QUEUED, RUNNING, SUCCEEDED, FAILED or CANCELED), attempts and maxAttempts, errorCode, the stored asset metadata (content type, size, checksum, expiry), webhookDeliveries (each with status, attempts and deliveredAt), and, for a succeeded job, a resultUrl.

The resultUrl here is signed for about 15 minutes. If it expires, read the job again to get a fresh one. GET /api/jobs lists the workspace's 50 most recent jobs, which is handy for a dashboard or a quick audit.

A reconciliation pattern that holds up:

  1. When you submit a job, store { ref, jobId, submittedAt, state: "pending" }.
  2. Mark the record done when a verified webhook arrives for that ref.
  3. On a schedule, poll any record still pending after a few minutes. A SUCCEEDED job whose webhook delivery shows FAILED is just a missed callback; take the resultUrl and continue.

Cancelling is also part of this API: DELETE /api/jobs/{id} cancels a queued job, or requests cancellation of a running one. A running browser may finish its current step before the worker discards the output.

Account usage webhooks

Separately from capture callbacks, the dashboard's account settings let you set a usage webhook URL. Screenshotly sends usage.warning when you cross your usage alert threshold (80% by default) and usage.limit when you reach the limit. The body is { "event", "timestamp", "data": { "usage", "limit" } }. These deliveries aren't signed, because no secret is configured for them, so treat them as notifications rather than authenticated commands. Pacing and limits are covered in the rate limits guide.

Checklist

  • Webhook in webhook.url, on Basic or higher, with a secret
  • Your own reference in the URL query or webhook.headers, stored next to the job ID
  • Raw-body HMAC check with constant-time compare; freshness checked on the body's timestamp
  • 2xx within 10 seconds, no redirects, heavy work moved off the request path
  • Dedupe on signature plus reference
  • Polling reconciliation for anything still pending
  • Copy files out of storageUrl / resultUrl before the retention period ends

For handling errors from the capture endpoints themselves, see the error handling guide. For fanning out many captures, see batch screenshot processing.

webhooks
async
events
integration

About the Author

Asad Ali

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 plan includes screenshot webhooks?

Webhook delivery requires the Basic plan or higher. A request that includes webhook.url on the Free plan is rejected with 403 and minimumPlan set to basic. Async jobs, which are where webhooks are most useful, also require Basic or higher.

How do I verify that a webhook came from Screenshotly?

Set webhook.secret on the capture request. Each delivery then carries X-Screenshotly-Signature: sha256=<hex>, an HMAC-SHA256 of the raw request body keyed with your secret. Recompute it over the exact bytes you received and compare in constant time. Without a secret, deliveries are unsigned.

How many times does Screenshotly retry a failed webhook?

Each delivery gets up to five attempts. An attempt succeeds only on a 2xx response within 10 seconds; redirects, timeouts and other statuses count as failures. Retries are scheduled at least 5, 15, 45 and 135 seconds apart, so the whole sequence typically finishes within a few minutes. After that the delivery is marked FAILED.

Does the webhook payload include the job ID?

No. The payload carries the event, a timestamp and capture data such as url, format, size, duration and, for completed captures with a stored result, storageUrl. Put your own reference in the webhook URL query string or in webhook.headers so you can match the callback to your record.

What happens if my endpoint is down for longer than the retry window?

The delivery is marked FAILED, but the capture result is still retained. Read GET /api/jobs/{id} to get the job status, a fresh short-lived resultUrl, and the webhook delivery status and attempt count.

Ready to capture your first screenshot?

Get started with 100 free screenshots. No credit card required.

Related Articles