Screenshot API Security: Auth, Rate Limiting & Data
What Screenshotly already enforces, what is left to your integration, and the code for the parts you own: key handling, a proxy that cannot be abused, webhook verification, and retention.
A screenshot API makes an outbound request on your behalf, runs a full browser against whatever URL it is given, and hands back a picture of everything on the page. Each of those steps is a security decision. Some are made for you by Screenshotly; others belong to your integration.
This guide separates the two, then gives working code for the parts you own. For the platform side in more detail, see how Screenshotly handles keys, URLs, and captures. The OWASP API Security Top 10 and the OWASP SSRF prevention cheat sheet are good background reading.
Who handles what
| Risk | Screenshotly enforces | You are responsible for |
|---|---|---|
| Stolen API key | Hashed storage, mandatory expiry, revocation, verified-email requirement | Keeping keys server-side, rotating them, revoking on exposure |
| SSRF through the target URL | Refuses private, loopback, link-local, and internal hostnames; checks every subrequest; refuses URLs with embedded credentials | Deciding which sites your users may capture; never fetching user URLs from your own servers |
| Abuse of your account through your app | Per-minute limits, plan gates, optional hard usage cap | Authenticating users, per-user limits, building requests from allowed fields only |
| Credential leakage in authenticated captures | Fresh browser per capture; cookie domain checks; encrypted job payloads | Choosing cookies over headers, using a read-only capture account, short sessions |
| Forged webhooks | HMAC-SHA256 signature when you set a secret | Verifying the signature and timestamp |
| Sensitive data in images | Captures stored only on request; expiring signed links; configurable retention | What you capture, what you hide, and how long you keep your own copies |
1. API keys
Keep the key on the server
The capture request carries your key, so it must come from server-side code. Anything shipped to a browser, including public build variables such as NEXT_PUBLIC_* or VITE_*, is readable by every visitor. Screenshotly's own playground does not accept cookies, headers, custom JavaScript, webhooks, or storage delivery for this reason; those require an account key.
For local development, a git-ignored .env file is fine:
# .env (add .env* to .gitignore before you create it)
SCREENSHOTLY_API_KEY=scr_...
In production, read the key from your platform's encrypted environment settings or a secrets manager. With AWS Secrets Manager and the v3 SDK:
import { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';
const client = new SecretsManagerClient({});
export async function getScreenshotlyKey() {
const { SecretString } = await client.send(
new GetSecretValueCommand({ SecretId: 'screenshotly/api-key' }),
);
return SecretString;
}
Cache the value in memory for the life of the process rather than fetching it on every capture.
One key per environment
A workspace can hold up to 10 active keys. Give development, CI, staging, and production their own keys and name them accordingly in Dashboard → API keys. When one leaks, you revoke one key instead of breaking every environment. If different teams or products need separate data, use separate workspaces: keys, jobs, and retained captures are scoped to the workspace that issued the key.
Plan for expiry and rotation
Keys created in the dashboard expire after 30 days, and expired keys return 401. Keys can only be created and revoked from a signed-in dashboard session, not with another API key, so rotation is a short manual routine:
- Create a new key in the same workspace.
- Store it in your secrets manager and deploy.
- Confirm traffic is succeeding with the new key (the dashboard's analytics show recent requests).
- Revoke the old key.
Put a reminder in your calendar a few days before each expiry date shown in the dashboard. If your code supports reading two keys during the overlap, keep that window short and remove the old key from configuration once it is revoked.
If a key leaks
Revoke it under Dashboard → API keys first; revocation takes effect on the next request. Then create a replacement and look at recent usage. A leaked key can spend quota and list the workspace's async jobs, including download links for files still inside the retention period, which is a good reason to keep retention short (section 5).
2. Proxying captures for your users
If your product lets users request screenshots, such as link previews or "capture this page" buttons, put your own endpoint in front of the API. Its job is to make sure your key can only be used the way you intend.
The most common mistake is forwarding the user's JSON body to Screenshotly. The request schema includes powerful fields: webhook.url sends results to any public address, javascript runs code in the page, cookies and headers impersonate users, and storage keeps files. A passthrough lets any user switch those on with your key. Build the upstream request from fields you choose:
import express from 'express';
const app = express();
app.use(express.json({ limit: '4kb' }));
const ALLOWED_HOSTS = new Set(['example.com', 'www.example.com', 'docs.example.com']);
const DEVICES = new Set(['desktop', 'laptop', 'tablet', 'mobile']);
// requireUser is your existing authentication middleware.
app.post('/api/preview', requireUser, async (req, res) => {
let target;
try {
target = new URL(String(req.body.url));
} catch {
return res.status(400).json({ error: 'Invalid URL' });
}
if (target.protocol !== 'https:' || !ALLOWED_HOSTS.has(target.hostname)) {
return res.status(400).json({ error: 'This site cannot be captured' });
}
// Only fields chosen here reach Screenshotly. Never forward req.body.
const body = {
url: target.href,
format: 'webp',
quality: 80,
device: DEVICES.has(req.body.device) ? req.body.device : 'desktop',
blockAds: true,
};
const upstream = 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(body),
});
if (!upstream.ok) {
// Do not pass upstream error details or headers through to the user.
return res.status(upstream.status === 429 ? 429 : 502).json({ error: 'Capture failed' });
}
res.type('image/webp').send(Buffer.from(await upstream.arrayBuffer()));
});
Add a per-user rate limit (for example, a Redis counter keyed by user ID) in front of this route. Screenshotly's limits apply to your whole workspace, so without your own limit one user can use up everyone's quota.
User-submitted URLs and SSRF
Server-side request forgery is the classic screenshot API risk: someone submits http://169.254.169.254/ or http://10.0.0.5/admin and the renderer captures an internal page. Screenshotly blocks this on its side. It refuses non-HTTP(S) schemes and URLs with embedded credentials, resolves the hostname, and rejects loopback, private, carrier-grade NAT, link-local, multicast, and reserved addresses in IPv4 and IPv6. Every request the page makes while rendering, including redirects and embedded resources, goes through the same check.
That leaves two things for you:
- Do not fetch user-supplied URLs from your own servers, for example to "check the page exists" before capturing. That request would come from your network, outside Screenshotly's protections, and is exactly the SSRF hole you are trying to avoid.
- Decide what may be captured at all. Blocking private networks does not stop someone using your feature to capture arbitrary public sites under your name and quota. If your product only needs your own or your customers' domains, use an allowlist like the one above.
3. Authenticated captures
Capturing logged-in pages means sending a session with the request, so the session becomes part of your attack surface. The short version:
- Send a session cookie rather than a header. Screenshotly sets cookies only for the target's domain, while custom headers are attached to every request the page makes, including third-party CDNs and analytics.
- Use a dedicated, read-only capture account, ideally in a demo tenant.
- Mint short-lived sessions per run and revoke them afterwards.
- Do not log capture request bodies.
The authenticated capture guide covers each method, the cookie fields, and how to make a request fail instead of capturing a login page.
4. Webhooks
When you set webhook.url (Basic and higher), Screenshotly POSTs a JSON event to that address: screenshot.completed with url, format, size, duration, and a storageUrl when the file was stored, or screenshot.failed with an error message. Without a secret, anyone who guesses your endpoint can post fake events to it.
Sign and verify every delivery
Add a long random secret to the request:
{
"url": "https://example.com",
"format": "pdf",
"storage": { "enabled": true },
"webhook": {
"url": "https://hooks.example.com/screenshotly",
"secret": "WEBHOOK_SECRET_FROM_YOUR_SECRET_STORE"
}
}
Generate it once, for example with openssl rand -hex 32, and keep it with your other secrets. Each delivery then includes:
X-Screenshotly-Signature: sha256=<hex>, an HMAC-SHA256 of the raw request body using your secret.X-Screenshotly-Timestamp, matching thetimestampfield inside the body.
Verify against the raw bytes; re-serializing parsed JSON can change them. In Express:
import crypto from 'node:crypto';
import express from 'express';
const app = express();
app.post('/screenshotly', express.raw({ type: 'application/json' }), (req, res) => {
const received = req.get('x-screenshotly-signature') ?? '';
const expected = 'sha256=' + crypto
.createHmac('sha256', process.env.SCREENSHOTLY_WEBHOOK_SECRET)
.update(req.body)
.digest('hex');
const valid = received.length === expected.length
&& crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected));
if (!valid) return res.sendStatus(401);
const event = JSON.parse(req.body.toString('utf8'));
// The timestamp is inside the signed body, so it cannot be altered.
const ageMs = Date.now() - Date.parse(event.timestamp);
if (!(ageMs >= 0 && ageMs < 60 * 60 * 1000)) return res.sendStatus(401);
res.sendStatus(204); // Acknowledge quickly, then process.
queueForProcessing(event); // your own job queue
});
Notes on the details:
- Retries resend the identical body. A delivery that fails or times out is retried with growing delays, up to 5 attempts, and every attempt carries the same timestamp and signature. Pick a freshness window that comfortably covers the retry schedule (one hour above), and deduplicate by storing the signatures you have already processed for that window.
- Respond within 10 seconds with any 2xx status. Deliveries time out after 10 seconds, and redirects are treated as failures, so point the webhook at the final URL.
- Usage alerts are different. The usage webhook you can set in dashboard settings (
usage.warningandusage.limitevents) is not signed. Treat it as a hint and confirm figures in the dashboard before acting on it.
5. Captured data
A screenshot contains whatever the page showed: names, email addresses, invoices, internal metrics. Treat captures with the same care as the source data.
Know where copies exist
| How you capture | Where the file lives | For how long |
|---|---|---|
| Synchronous request (default) | Only in the response you receive | Not stored by Screenshotly |
cache: true (Basic+) |
Screenshotly's cache | The cacheTtl you set, 60 seconds to 24 hours |
storage.enabled or async jobs (Basic+) |
Screenshotly object storage, under your workspace | The workspace owner's retention setting: 7 days by default, 1–30 configurable |
Some consequences:
- Set retention to the shortest period that works in the workspace owner's dashboard settings. Each file's expiry is fixed when it is captured, so a shorter setting applies to later captures. Stored files are reachable through job results until they expire.
- Signed links are bearer links. The
urlreturned by storage delivery, and thestorageUrlin webhooks, work for anyone who has them for 24 hours. Do not post them in public channels or tickets; download the file and keep your own controlled copy if you need it longer. JobresultUrllinks last 15 minutes. - Cached responses are marked
Cache-Control: public. Do not enablecachefor private pages if the response passes through a shared CDN or proxy on your side.
Hide sensitive elements before capture
If you capture pages for documentation or reports, hide personal data in the page rather than blurring it afterwards. On Growth and higher, hideSelectors removes matching elements before the screenshot is taken:
{
"url": "https://app.example.com/settings/billing",
"format": "png",
"hideSelectors": [".customer-email", "[data-sensitive]", "#card-last4"],
"cookies": [{ "name": "session", "value": "SESSION_VALUE" }]
}
Better still, capture a demo account whose data was never real.
Your own storage
When you keep captures yourself, use a private bucket, serve them through short-lived signed URLs, enable your provider's server-side encryption, and let a lifecycle rule delete them on schedule. On S3:
{
"Rules": [
{
"ID": "expire-screenshots",
"Status": "Enabled",
"Filter": { "Prefix": "screenshots/" },
"Expiration": { "Days": 30 }
}
]
}
6. Spend and abuse limits
Limits are a security control: they cap the damage from a leaked key or a runaway loop.
- Plan limits. Free allows 5 requests per minute and 100 captures in total; Basic 40 per minute and 2,500 a month; Growth 80 and 12,000; Scale 200 and 50,000. Going over either returns
429with aRetry-Afterheader. - Hard usage limit. In dashboard settings you can set a monthly cap below your plan allowance (up to 50,000). Captures stop with
429when it is reached, and there are no automatic overage charges. - Usage alerts. Choose an alert threshold between 50% and 100% of the effective limit to get a notification and email before you hit it.
- Failed requests are free. Errors do not consume quota, so a sudden rise in successful usage that you did not cause is a strong signal that a key has leaked.
When you handle 429, treat a long Retry-After as "quota exhausted" and stop rather than retrying in a loop. The rate limits guide has patterns.
Checklist
Before launch
- Keys are read only by server-side code, from a secrets manager or encrypted environment settings
- Separate keys per environment; separate workspaces where data must not mix
- Rotation reminder set before each key's expiry date
- User-facing endpoints authenticate users, rate-limit per user, and build requests from allowed fields only
- A domain allowlist if users may submit URLs
- Your servers never fetch user-supplied URLs themselves
- Authenticated captures use cookies for a read-only account with short sessions
- Webhooks use a secret; the receiver verifies signature and timestamp and deduplicates
- Retention set to the shortest workable period; caching off for private pages behind shared caches
- Hard usage limit and alert threshold configured
Ongoing
- Rotate keys before expiry; revoke immediately on any exposure
- Review usage in the dashboard for unexpected growth
- Re-check the domain allowlist when your product changes
- Keep webhook and capture-account secrets in rotation with your other credentials
Summary
Screenshotly blocks private-network targets, isolates each render, hashes and expires keys, encrypts queued payloads, signs webhooks on request, and deletes stored files on schedule. Your integration still decides who can trigger captures, which fields and sites they can use, how keys and webhook secrets are stored, and how long captured data lives on your side. Get those right and the API adds very little risk to your stack.
Building a secure integration? Create a free account to test the request shape with 100 free captures. Start with your first request, and report security issues privately to security@screenshotly.app.
See also: Error Handling Guide
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
Where should the Screenshotly API key live in production?
In a secrets manager or your platform's encrypted environment variables, loaded only by server-side code. Never put it in browser JavaScript, in public build variables such as NEXT_PUBLIC_* or VITE_*, or in source control. Keys created in the dashboard expire after 30 days, so plan the rotation from day one.
Do I still need to block private IP addresses if Screenshotly already does?
Not for Screenshotly's sake. The API refuses targets that resolve to loopback, private, link-local, or other non-public addresses and checks every request the page makes while rendering. What you still own is product policy: which domains your users may capture at all, and making sure your own server never fetches user-supplied URLs itself.
How do I let end users request screenshots without exposing my key?
Put a backend endpoint in front of the API. It authenticates the user, applies a per-user rate limit, checks the URL against your policy, and builds the Screenshotly request from an allowlist of fields before adding the key. Never forward the user's JSON as-is.
How do I verify that a webhook really 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. Recompute it over the raw bytes, compare in constant time, and check the timestamp inside the body. Usage alert webhooks configured in dashboard settings are not signed.
What can someone do with a leaked API key?
Spend your capture quota, use any feature your plan includes, and list the workspace's async jobs, including fresh download links for files that are still within the retention period. Revoke the key in the dashboard immediately, then set a hard usage limit and a short retention period to cap the damage from any future leak.
Ready to capture your first screenshot?
Get started with 100 free screenshots. No credit card required.