Cloudflare 16 ☁️ Cloudflare Images & Turnstile — Transforming/optimizing media on demand and replacing CAPTCHAs with privacy-first bot checks
Two problems that look unrelated end up in the same chapter because they fail in the same way: an image pipeline that ships the wrong bytes to the right person, and a bot check that ships the wrong experience to a human. Both are Cloudflare products whose value is that they move work off the origin, and both have a cost model or a trust model that is easy to get wrong in a way that does not show up until the invoice arrives or the abuse starts.
The image side is really three products wearing one name. Polish recompresses images that already live on your zone, at the same URL, with no storage and no per-image billing. Transformations — the /cdn-cgi/image/<options>/<source> path — resizes and re-encodes an image from your origin on demand, and is billed per unique transformation rather than per request. Cloudflare Images stores the original at Cloudflare, serves it from imagedelivery.net through named variants, and bills on storage, delivery, and transformations together. Choosing between them is a question about where the original lives and who is allowed to change its size.
The bot side is Turnstile, which replaces reCAPTCHA and hCaptcha with a challenge that usually resolves without any user interaction and without the tracking cookie the alternatives set. Its entire security model fits in two sentences: the browser receives a short-lived token that it cannot forge, and your server exchanges that token for a verdict. Every mistake with Turnstile comes from treating the first half as if it were the second.
This chapter walks through the three image products and the variant model that drives their billing, then the transformation URL and the option-space problem that turns an open query string into an unbounded bill, then the Turnstile widget, the token lifecycle, and the siteverify call that is the only place the verdict is trusted. The final section covers the abuse controls that belong around both: cache keys, rate limits, and the difference between a bot signal and a rate limiter.
Key point: Images and Turnstile both charge or trust on a dimension an attacker can drive — Images bills per unique transformation, so an open option string is a bill, and Turnstile issues a single-use token whose only trustworthy validation is the server-side siteverify call, so the client callback is cosmetic.
Why it exists
The origin-image problem. An origin server that stores one 4000×3000 JPEG and serves it as a 120-pixel avatar is shipping roughly a hundred times the bytes the page needs, and it is doing it on every request because the CDN caches what the origin gave it. The fix is not to pre-generate every size — that is a storage problem, a backfill problem, and a problem that grows by one dimension each time a designer adds a breakpoint. The fix is to transform on request and let the edge cache the result, which is what both Transformations and Images do.
The format-negotiation problem. JPEG is not the right answer to any request in 2025, but the right answer differs per client: AVIF where it is supported, WebP where it is not, JPEG where neither is. Doing that negotiation in the origin means parsing Accept, maintaining three encodes, and hoping a proxy does not strip the header. Doing it at the edge with format=auto means the negotiation happens once per cache key on the path that already has the image in memory.
The variant-proliferation problem. Every transformation option combination is a distinct artifact, and Cloudflare bills transformations by the count of unique combinations rather than by the number of requests. That is generous and correct for a site that uses five presets, and it is a denial-of-wallet vector for a site that accepts the option string from a query parameter — one attacker with one source image and a loop over width=1..5000 creates five thousand billable uniques that no rate limiter will see, because each request is a single cache miss followed by a single cache hit for anyone else.
The CAPTCHA-privacy problem. reCAPTCHA and hCaptcha work by collecting behavioural and device signals and, in reCAPTCHA’s case, by tying the verdict to a Google account session that most users hold without knowing it. That is a third-party tracker on every form with a checkbox. Turnstile’s pitch is that it reaches a verdict from the challenge interaction itself — a small proof of work plus browser attestation — without setting a tracking cookie on the standard widget, which is why it can be deployed on pages where a consent banner for reCAPTCHA would otherwise be required.
The accessibility problem. An image grid of traffic lights is a barrier for a large set of users, and the audio alternative is itself a barrier for others. Accessibility is not a nice-to-have here; a challenge that cannot be completed is a login that cannot be completed. Turnstile’s managed widget resolves for most users without any interaction at all, and falls back to a checkbox rather than a puzzle when it is uncertain.
The client-trust problem. Turnstile’s JavaScript callback fires on success, and the obvious implementation — disable the submit button until the callback fires — is not a security control, because the callback runs in the attacker’s browser under the attacker’s control. The token is evidence; the verdict is the server’s exchange of that evidence with Cloudflare. Any application that skips the exchange has built a client-side CAPTCHA, which is to say a suggestion.
The trade-off. Every control in this chapter narrows something legitimate. A closed preset map means a new image size is a deploy. Signed delivery URLs mean a token to generate for every consumer. Turnstile means a network dependency in the login path, and a Cloudflare outage is a login outage unless the failure path is designed. The design question is which narrowings cost less than the alternative they prevent.
a. The three image products and the variant model
The choice between them is a question of where the original lives.
┌──────────────────────────────────────────────────────────┐
│ WHICH PRODUCT DOES WHAT │
│ │
│ origin image on your zone │
│ │ │
│ ├──► Polish recompress in place │
│ │ same URL, no storage │
│ │ │
│ └──► Transform /cdn-cgi/image/... │
│ resize on request │
│ │
│ image uploaded to Images │
│ │ │
│ └──► Delivery imagedelivery.net/hash/id/name │
│ named + flexible variants │
└──────────────────────────────────────────────────────────┘
Uploading to Images is a multipart POST to the account-scoped API. The id field is optional; supplying it means the delivery URL is predictable and idempotent rather than opaque.
// Upload one image to Cloudflare Images and control its identifier
const form = new FormData();
form.append("file", blob, "hero.jpg");
// Optional: a caller-chosen id makes the delivery URL deterministic
form.append("id", "hero-2025-03");
// Opt in to signed delivery for this image specifically
form.append("requireSignedURLs", "false");
// Metadata is searchable and comes back on the list endpoint
form.append("metadata", JSON.stringify({ section: "home", alt: "Team photo" }));
const res = await fetch(
`https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/images/v1`,
{ method: "POST", headers: { Authorization: `Bearer ${TOKEN}` }, body: form },
);
const { result } = await res.json();
// The delivery URL is built from the account hash, the id, and a variant name
const url = `https://imagedelivery.net/${ACCOUNT_HASH}/${result.id}/hero`;
When the browser must upload directly rather than through your Worker — a large file, a mobile client, a form that should not proxy bytes — the API issues a one-time upload URL. The client POSTs to it, and your Worker never sees the file.
// Ask Cloudflare for a single-use upload URL bound to this session
const r = await fetch(
`https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/images/v1/direct_upload`,
{
method: "POST",
headers: { Authorization: `Bearer ${TOKEN}`, "Content-Type": "application/json" },
// Metadata and signed-URL policy are fixed here, not by the client
body: JSON.stringify({ requireSignedURLs: true, metadata: { uploader: userId } }),
},
);
const { result } = await r.json();
// result.uploadURL is single-use; hand it to the client and forget it
return Response.json({ uploadURL: result.uploadURL, id: result.id });
A variant is a named set of transformation options stored on the account. Accounts can hold a bounded number of named variants, which is the intended model: designers pick sizes, and the names become part of the delivery URL. Flexible variants drop the name and accept options in the URL directly, which is convenient and which is the billing surface discussed in the next section.
// A named variant is created once; the delivery URL then uses the name
await fetch(
`https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/images/v1/variants`,
{
method: "POST",
headers: { Authorization: `Bearer ${TOKEN}`, "Content-Type": "application/json" },
body: JSON.stringify({
id: "card", // becomes the last path segment
neverRequireSignedURLs: false,
options: {
fit: "cover", // crop to fill rather than letterbox
width: 400,
height: 300,
// `auto` negotiates AVIF or WebP from the Accept header
format: "auto",
quality: 80,
// `face` uses Cloudflare's detector; a fractions pair also works
gravity: "auto",
},
}),
},
);
fit decides what happens when the aspect ratio does not match: scale-down never enlarges, contain letterboxes, cover fills the box and crops, crop crops to the requested dimensions, and pad fills the remainder with background. gravity decides which part survives the crop — auto uses saliency, face uses detection, and a 0.5x0.5 pair places the crop centre manually. metadata=none strips EXIF, which is the correct default for user-uploaded images because EXIF routinely carries GPS coordinates.
b. Transformations, the option space, and the bill it creates
The /cdn-cgi/image/ path applies options to an image your origin already serves, with no upload and no storage. The grammar is the options, comma-separated, then the absolute source URL.
/cdn-cgi/image/width=800,quality=75,format=auto/https://example.com/photo.jpg
The cache key is the whole transformation URL, and the whole transformation URL includes the source URL — query string and all. That has two consequences worth stating plainly. First, a cache-busting ?v=123 on the source produces a different transformation, so a deployment that appends one to every image invalidates the transform cache along with the origin cache. Second, and more importantly, the count of distinct transformation URLs is what the plan bills, so anything that lets a caller vary the URL increases cost.
// The amplifier: the option string is taken from the request
const opts = new URL(req.url).searchParams.get("opts") ?? "width=800";
// Every distinct `opts` value is a unique, billable transformation
return fetch(`https://example.com/cdn-cgi/image/${opts}/${sourceUrl}`);
A single caller iterating width=1..5000 produces five thousand uniques in seconds, each of which is one origin fetch and then a cached artifact nobody asked for. The requests are individually cheap, individually well-formed, and individually unremarkable to a rate limiter that counts requests rather than distinct URLs.
// The fix: a closed preset map, keyed by a short segment of the path
const PRESETS: Record<string, string> = {
// Each entry is one billable unique regardless of how much traffic it gets
thumb: "width=200,height=200,fit=cover,quality=70,format=auto",
card: "width=400,height=300,fit=cover,quality=80,format=auto",
hero: "width=1600,quality=80,format=auto",
og: "width=1200,height=630,fit=cover,quality=85,format=auto",
};
// The raw option string never reaches the URL; only a key does
function buildTransform(preset: string, source: string): string | null {
const opts = PRESETS[preset];
if (!opts) return null; // reject, do not default
// Strip cache-busting params from the source so the unique stays stable
const clean = new URL(source);
clean.search = "";
return `https://example.com/cdn-cgi/image/${opts}/${clean.toString()}`;
}
Named variants on Images enforce the same closed set structurally, which is why they are the safer default when the original is already at Cloudflare. Flexible variants should be enabled deliberately and, if enabled, fronted by a Worker that validates the option string against an allowlist of keys and a bounded integer range for each.
Two related products are worth distinguishing because they are commonly confused with transformations. Polish recompresses the image your origin already serves for that URL with no resizing, so it does not create new artifacts or new uniques; it is a compression toggle. The Images binding in Workers exposes the same transform engine as an in-process API on an upload stream, which is the right tool for generating a one-off derivative during a write rather than on a read.
Response caching deserves its own line, because it determines whether the transformation cost is paid once or repeatedly. A transformed image is cacheable at the edge like any other asset, and the origin should return a long Cache-Control so the transformed result does not revalidate. A private or user-specific image is the exception: it should be served through a signed URL rather than a public variant, so the cache key includes the authorisation.
// Signed delivery: HMAC over the image id and the expiry, hex-encoded
async function signedUrl(imageId: string, variant: string, key: string) {
const exp = Math.floor(Date.now() / 1000) + 3600; // one hour
const enc = new TextEncoder();
const cryptoKey = await crypto.subtle.importKey(
"raw", enc.encode(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign"],
);
// The string to sign is the image id concatenated with the expiry
const sig = await crypto.subtle.sign("HMAC", cryptoKey, enc.encode(imageId + exp));
const hex = [...new Uint8Array(sig)].map(b => b.toString(16).padStart(2, "0")).join("");
// Both the expiry and the signature travel in the query string
return `https://imagedelivery.net/${ACCOUNT_HASH}/${imageId}/${variant}?exp=${exp}&sig=${hex}`;
}
c. Turnstile — the widget, the token, and the verdict
The widget renders, solves something, and hands the page a token. The token is valid for five minutes and usable once. Everything that follows is about not wasting that.
<!-- Implicit rendering: the script finds every .cf-turnstile on the page -->
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
<form method="post" action="/login">
<input name="email" type="email" required autocomplete="username">
<div
class="cf-turnstile"
data-sitekey="0x4AAAAAAA_yoursitekey"
data-action="login"
data-cdata="sess_9f2a41"
data-theme="auto"
data-size="flexible"
></div>
<button type="submit">Sign in</button>
</form>
The data-action and data-cdata attributes are not decoration. Both are folded into the token and echoed back on verification, which lets the server confirm that the token was minted for this form and this session rather than replayed from a page the attacker controls. action is a short label, cdata a short opaque value; both come back in the siteverify response and both must be compared against what your server expects.
// Explicit rendering when the widget must be reset or moved by the app
turnstile.render("#challenge", {
sitekey: "0x4AAAAAAA_yoursitekey",
action: "signup",
theme: "auto",
// Refresh automatically if the token ages out while the form is open
"refresh-expired": "auto",
callback: (token) => { state.token = token; },
"error-callback": () => { state.token = null; showRetry(); },
"expired-callback": () => { state.token = null; },
});
// A widget can be reset when the form is resubmitted after a validation error
turnstile.reset("#challenge");
The verification call is a form-encoded POST with the secret, the token, and optionally the end-user IP. It must happen server-side, and it must happen before the action, not after.
// The only place the token is trusted: the server-side exchange
async function verifyTurnstile(token: string, ip: string, env: Env) {
const body = new URLSearchParams({
secret: env.TURNSTILE_SECRET, // never sent to the browser
response: token, // the cf-turnstile-response field
remoteip: ip, // CF-Connecting-IP, for the record
});
const r = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
method: "POST",
body, // Content-Type is inferred for URLSearchParams
});
const out = await r.json() as {
success: boolean;
"error-codes"?: string[];
action?: string;
cdata?: string;
hostname?: string;
};
if (!out.success) return { ok: false, reason: out["error-codes"] };
// The action must match the form that was rendered, not just any form
if (out.action !== "login") return { ok: false, reason: ["action_mismatch"] };
// The cdata binds the token to this session and defeats cross-session replay
if (out.cdata !== expectedSessionId) return { ok: false, reason: ["cdata_mismatch"] };
return { ok: true };
}
The error codes are the diagnostic surface, and two of them matter operationally. timeout-or-duplicate means the token was used twice or aged past its five minutes — in practice almost always a double submit from a slow form, so the UI should reset the widget rather than the user being told they are a robot. invalid-input-response means the token was malformed or already consumed by another verification, which is the signature of a programmatic submit. Treating every failure as “bot” produces a support queue; mapping the code to a recovery path produces a login.
// Distinguish a retryable failure from a rejected one
const v = await verifyTurnstile(token, ip, env);
if (!v.ok) {
const codes = v.reason ?? [];
if (codes.includes("timeout-or-duplicate")) {
// The user took too long or double-clicked: reset and let them retry
return Response.json({ error: "challenge_expired", retry: true }, { status: 409 });
}
// Anything else is a failed check, not a failed form
return new Response("forbidden", { status: 403 });
}
Three widget behaviours cover the deployment patterns. Managed is the default and the recommended one: it decides per visitor whether to challenge silently, show a checkbox, or show an interactive prompt. Non-interactive runs the challenge without ever showing a checkbox, which is appropriate for low-risk actions and inappropriate for a login. Invisible keeps the widget out of the layout entirely and is triggered programmatically, which is the right choice when the check runs on submit rather than on render.
// Invisible widget: the challenge runs when you ask it to
const widgetId = turnstile.render("#hidden", {
sitekey: "0x4AAAAAAA_yoursitekey",
size: "invisible",
action: "checkout",
callback: (token) => submitForm(token),
});
// Only now does the challenge solve, and only now is there a token
form.addEventListener("submit", (e) => { e.preventDefault(); turnstile.execute(widgetId); });
d. Abuse controls, cost drivers, and the failure path
Neither product is a rate limiter, and treating one as a limiter is the most common architectural mistake in this chapter.
// A Worker that front-loads the cheap checks before the expensive work
export default {
async fetch(req: Request, env: Env) {
// 1. Coarse per-IP limit at the edge, before parsing anything
const ip = req.headers.get("CF-Connecting-IP") ?? "unknown";
if (!(await env.LIMITER.limit({ key: `ip:${ip}` })).success) {
return new Response("too many requests", { status: 429 });
}
const body = await req.formData();
// 2. The token exchange happens before any database work
const token = String(body.get("cf-turnstile-response") ?? "");
if (!token) return new Response("missing token", { status: 400 });
const verdict = await verifyTurnstile(token, ip, env);
if (!verdict.ok) return new Response("forbidden", { status: 403 });
// 3. Only now is it worth hashing a password or touching the database
return handleLogin(body, env);
},
};
Turnstile answers “is this a browser running a real challenge”, not “how many times has this IP asked”. A credential-stuffing run that solves the challenge correctly on every attempt is a legitimate Turnstile success and an attack, so the per-account and per-IP limits sit alongside it rather than being replaced by it. The honest framing is that Turnstile raises the cost of automation and the limiter bounds the volume; either one alone is insufficient.
On the image side, the cost levers are the same shape. Named variants instead of flexible ones, a preset map instead of an option string, a stripped query string on the source URL, and a long Cache-Control on the transformed response so the unique is paid for once. A Worker that proxies transformations should reject any preset it does not recognise rather than falling back to a default, because a fallback is still a fetch and a fetch on an unloved path is still billed.
// Reject unknown presets outright; a default is a bill you did not choose
const preset = url.pathname.split("/")[2];
if (!Object.hasOwn(PRESETS, preset)) {
return new Response("unknown preset", { status: 404 });
}
The failure path matters for Turnstile specifically because it is in the login path. If siteverify is unreachable, the correct behaviour depends on the form: a password reset can reasonably fail closed, and a read-only action can reasonably proceed. What must not happen is a catch that returns { ok: true } to keep the form working, which is a permanent bypass installed during an outage and never removed.
// Fail closed on the login path, and say so rather than silently allowing
try {
return await verifyTurnstile(token, ip, env);
} catch (err) {
// Log for the on-call; do not degrade the control to keep the form green
console.error("siteverify unreachable", { err, ip });
return { ok: false, reason: ["verifier_unavailable"] };
}
Complete Example Session
// ============================================
// PART 1: THE BINDING AND THE PRESET MAP
// ============================================
// wrangler.jsonc declares the rate-limit binding and the secrets
// { "vars": { "ACCOUNT_HASH": "abc123" },
// "unsafe": { "bindings": [{ "name": "LIMITER", "type": "ratelimit",
// "namespace_id": "1001", "simple": { "limit": 30, "period": 60 } }] } }
const PRESETS: Record<string, string> = {
thumb: "width=200,height=200,fit=cover,quality=70,format=auto",
hero: "width=1600,quality=80,format=auto",
og: "width=1200,height=630,fit=cover,quality=85,format=auto",
};
// ============================================
// PART 2: THE UPLOAD HANDLER
// ============================================
async function upload(req: Request, env: Env) {
const inForm = await req.formData();
const file = inForm.get("file") as File;
const out = new FormData();
out.append("file", file, file.name);
// The id is derived server-side so the client cannot choose a path
out.append("id", `up-${crypto.randomUUID()}`);
out.append("requireSignedURLs", "false");
return fetch(
`https://api.cloudflare.com/client/v4/accounts/${env.ACCOUNT_ID}/images/v1`,
{ method: "POST", headers: { Authorization: `Bearer ${env.API_TOKEN}` }, body: out },
);
}
// ============================================
// PART 3: THE PRESET PROXY
// ============================================
// /img/<preset>/<path> -> /cdn-cgi/image/<opts>/<origin path>
function transformUrl(reqUrl: URL, env: Env): string | null {
const [, , preset, ...rest] = reqUrl.pathname.split("/");
const opts = PRESETS[preset];
if (!opts) return null; // unknown preset: reject
const source = new URL(`/${rest.join("/")}`, env.ORIGIN);
source.search = ""; // strip cache-busting params
return `https://${env.ZONE}/cdn-cgi/image/${opts}/${source.toString()}`;
}
// ============================================
// PART 4: THE SIGNED DELIVERY URL
// ============================================
async function signedUrl(imageId: string, variant: string, key: string, hash: string) {
const exp = Math.floor(Date.now() / 1000) + 3600;
const enc = new TextEncoder();
const k = await crypto.subtle.importKey(
"raw", enc.encode(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign"],
);
const sig = await crypto.subtle.sign("HMAC", k, enc.encode(imageId + exp));
const hex = [...new Uint8Array(sig)].map(b => b.toString(16).padStart(2, "0")).join("");
return `https://imagedelivery.net/${hash}/${imageId}/${variant}?exp=${exp}&sig=${hex}`;
}
// ============================================
// PART 5: THE CHALLENGE PAGE
// ============================================
const PAGE = `<!doctype html>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
<form method="post" action="/login">
<input name="email" type="email" required>
<div class="cf-turnstile" data-sitekey="SITEKEY"
data-action="login" data-cdata="SESSIONID" data-size="flexible"></div>
<button>Sign in</button>
</form>`;
// ============================================
// PART 6: THE VERIFICATION CALL
// ============================================
async function siteverify(token: string, ip: string, env: Env) {
const body = new URLSearchParams({
secret: env.TURNSTILE_SECRET, // server-side only
response: token,
remoteip: ip,
});
const r = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify",
{ method: "POST", body });
return r.json();
}
// ============================================
// PART 7: THE ACTION AND CDATA ASSERTIONS
// ============================================
async function check(token: string, ip: string, session: string, env: Env) {
const out = await siteverify(token, ip, env);
if (!out.success) return { ok: false, codes: out["error-codes"] };
// The token must belong to this form and this session
if (out.action !== "login" || out.cdata !== session) {
return { ok: false, codes: ["binding_mismatch"] };
}
return { ok: true };
}
// ============================================
// PART 8: THE FAILURE PATHS
// ============================================
async function loginHandler(req: Request, env: Env, session: string) {
const form = await req.formData();
const token = String(form.get("cf-turnstile-response") ?? "");
if (!token) return new Response("missing token", { status: 400 });
let verdict;
try {
verdict = await check(token, req.headers.get("CF-Connecting-IP") ?? "", session, env);
} catch {
// Fail closed: never return ok:true to keep the form green
return new Response("verification unavailable", { status: 503 });
}
if (!verdict.ok) {
// A duplicate submit is a retry, not a bot; tell the client to reset
if (verdict.codes?.includes("timeout-or-duplicate")) {
return Response.json({ retry: true }, { status: 409 });
}
return new Response("forbidden", { status: 403 });
}
return authenticate(form, env);
}
// ============================================
// PART 9: THE CACHE HEADER
// ============================================
// Pay the transformation unique once, then serve it from the edge
// Cache-Control: public, max-age=31536000, immutable
// -> the optimised bytes are reused for every subsequent request
// Cache-Control: private, max-age=300
// -> for signed / per-user images; the authorization is the cache key
// ============================================
// PART 10: THE AUDIT LINE
// ============================================
console.log(JSON.stringify({
event: "turnstile.verify",
ip, // from CF-Connecting-IP
action: "login",
ok: verdict.ok,
codes: verdict.codes ?? [], // the error code, not the token
ts: Date.now(),
}));
The ten parts covered the preset map that bounds the transformation count, the server-side upload, the proxy that rejects unknown presets, the HMAC signed delivery URL, the challenge page with action and cdata bound, the siteverify exchange, the assertions that make the token single-purpose, the failure paths that fail closed and still allow a retry, the cache header that decides whether the unique is paid once, and the audit line that records the verdict without recording the token.
Quick Reference
The Three Image Products
| Product | Original Lives | Billed On |
|---|---|---|
| Polish | Your zone | Plan feature, no per-image |
| Transformations | Your zone | Per unique transformation |
| Images | Cloudflare | Storage + delivery + transforms |
Variant and Transformation Options
| Option | Values | Effect |
|---|---|---|
width / height | px | Target dimensions |
fit | scale-down, contain, cover, crop, pad | Aspect-ratio behaviour |
gravity | auto, face, left, top, 0.5x0.5 | Crop origin |
format | auto, avif, webp, json, jpeg, png | Encoding |
quality | 1–100 | Compression strength |
dpr | 1, 2, 3 | Device-pixel ratio |
metadata | none, keep, copyright | EXIF handling |
background | hex, transparent | Padding fill |
Turnstile Widget Types
| Type | Interaction | data-size |
|---|---|---|
| Managed | Decided per visitor | normal, compact, flexible |
| Non-interactive | Never shows a checkbox | same |
| Invisible | Programmatic via turnstile.execute | none |
Siteverify Response and Errors
| Field / Code | Meaning |
|---|---|
success | Verdict; the only field that gates |
action | Echo of data-action; must be validated |
cdata | Echo of data-cdata; must be validated |
hostname | Site the token was minted for |
challenge_ts | ISO timestamp of the solve |
timeout-or-duplicate | Token aged out or already used |
invalid-input-response | Malformed or consumed token |
Cost and Abuse Levers
| Lever | Controls |
|---|---|
| Named variants | Bounds the transformation set structurally |
| Preset map in a Worker | Rejects unknown option strings |
| Stripped source query | Keeps the unique stable across deploys |
Long Cache-Control | Pays a unique once, not per request |
| Per-IP edge limit | Bounds request volume |
| Turnstile | Raises automation cost, not volume |
Best Practices
✅ Do This:
// Named variants for public images
{ id: "card", options: { fit: "cover", width: 400, format: "auto" } } // ✅
// Closed preset map; reject unknown keys
if (!Object.hasOwn(PRESETS, preset)) return new Response("", { status: 404 }); // ✅
// Strip the source query so the unique stays stable
source.search = ""; // ✅
// Sign private deliveries with HMAC over id + exp
crypto.subtle.sign("HMAC", k, enc.encode(imageId + exp)); // ✅
// Bind the token to the form and the session
if (out.action !== "login" || out.cdata !== session) reject(); // ✅
// Verify server-side, before any expensive work
const out = await siteverify(token, ip, env); // ✅
// Distinguish a retryable failure from a rejection
if (codes.includes("timeout-or-duplicate")) return retryPrompt(); // ✅
// Fail closed when the verifier is unreachable
catch { return new Response("unavailable", { status: 503 }); } // ✅
// Rate-limit alongside Turnstile, not instead of it
await env.LIMITER.limit({ key: `ip:${ip}` }); // ✅
❌ Don’t Do This:
// The option string straight from the query
const opts = url.searchParams.get("opts"); // ❌
// Enabling flexible variants without fronting them
// (any caller can invent a width, and each is billable) // ❌
// Defaulting an unknown preset instead of rejecting it
const opts = PRESETS[p] ?? PRESETS.thumb; // ❌
// Cache-busting params that multiply the uniques
`/cdn-cgi/image/${opts}/${src}?v=${commitSha}` // ❌
// Trusting the client callback
turnstile.render(el, { callback: () => enableSubmit(true) }); // ❌
// Disabling the submit button as the security control
if (!token) button.disabled = true; // ❌
// Verifying after the database write
await db.insert(user); await siteverify(token); // ❌
// Swallowing a verifier outage to keep the form green
catch { return { ok: true }; } // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Transformation bill spike | Option string taken from the request | Preset map, reject unknown |
| Cache miss on every request | Cache-busting param in the source URL | Strip the source query |
| Private image publicly served | Public variant used for user data | Signed URL with exp/sig |
| GPS coordinates in the output | EXIF preserved on upload | metadata=none |
| Token replay across forms | action not validated | Compare action and cdata |
| Bot check bypassed | Only the client callback checked | Server-side siteverify |
| Users told they are robots | All errors mapped to 403 | Branch on timeout-or-duplicate |
| Login down with Cloudflare | catch returned ok: true | Fail closed, surface 503 |
| Challenge never shown | Widget rendered inside a hidden form | Render on submit, execute |
Real-World Examples
1. Upload with a chosen id
form.append("id", `hero-${yearMonth}`); // deterministic delivery URL
2. Direct creator upload
POST /accounts/{id}/images/v1/direct_upload // one-time URL, policy fixed server-side
3. Format negotiation
options: { format: "auto", quality: 80 } // AVIF or WebP from Accept
4. Preset lookup
const opts = PRESETS[preset];
if (!opts) return new Response("", { status: 404 });
5. Signed delivery
`?exp=${exp}&sig=${hmacHex(imageId + exp)}`
6. Widget with binding
<div class="cf-turnstile" data-sitekey="..." data-action="login" data-cdata="sess_9f2a">
7. Server verification
POST https://challenges.cloudflare.com/turnstile/v0/siteverify
8. Binding assertion
if (out.action !== "login" || out.cdata !== session) return 403;
9. Retry on duplicate
if (codes.includes("timeout-or-duplicate")) return retryPrompt();
10. Edge limit first
if (!(await env.LIMITER.limit({ key: `ip:${ip}` })).success) return 429;
Visual
Which Product Does What
┌──────────────────────────────────────────────────────────┐
│ WHICH PRODUCT DOES WHAT │
│ │
│ origin image on your zone │
│ │ │
│ ├──► Polish recompress in place │
│ │ same URL, no storage │
│ │ │
│ └──► Transform /cdn-cgi/image/... │
│ resize on request │
│ │
│ image uploaded to Images │
│ │ │
│ └──► Delivery imagedelivery.net/hash/id/name │
│ named + flexible variants │
└──────────────────────────────────────────────────────────┘
Why an Open Option String Is a Bill
┌──────────────────────────────────────────────────────────┐
│ WHY AN OPEN OPTION STRING IS A BILL │
│ │
│ /cdn-cgi/image/width=800/photo.jpg ── unique #1 │
│ /cdn-cgi/image/width=801/photo.jpg ── unique #2 │
│ /cdn-cgi/image/width=802/photo.jpg ── unique #3 │
│ ... one attacker, one URL, 5000 widths │
│ │
│ FIX: a closed preset map │
│ │
│ /img/thumb/photo.jpg ──► width=200,format=auto │
│ /img/hero/photo.jpg ──► width=1600,format=auto │
│ /img/og/photo.jpg ──► 1200x630,fit=cover │
│ │
│ three presets, three uniques, whatever the traffic │
└──────────────────────────────────────────────────────────┘
Turnstile Token Lifecycle
┌──────────────────────────────────────────────────────────┐
│ TURNSTILE TOKEN LIFECYCLE │
│ │
│ t+0 widget renders on the page │
│ t+1s challenge solved, token issued │
│ t+2s form POSTs token to your worker │
│ t+3s worker calls siteverify │
│ t+4s success=true, action=login, cdata=sess_9f2a │
│ t+5s worker checks action and cdata, then proceeds │
│ │
│ t+300s token expires; reuse returns timeout-or-dup │
│ any second use of the same token is rejected │
│ │
│ reject the request if success is false OR the action │
│ does not match the form OR cdata does not match the │
│ session. All three, every time. │
└──────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Image storage + delivery | Cloudflare Images, imagedelivery.net |
| On-demand resize | /cdn-cgi/image/<options>/<source> |
| In-place recompression | Polish |
| Delivery URL shape | imagedelivery.net/<hash>/<id>/<variant> |
| Variant count model | Bounded named variants, optional flexible |
| Signed delivery | HMAC-SHA256 over imageId + exp, sig in query |
| Transform billing unit | Unique transformation, not request |
| Turnstile token lifetime | 300 seconds, single use |
| Verification endpoint | challenges.cloudflare.com/turnstile/v0/siteverify |
| Token binding fields | action and cdata, echoed back |
| Widget types | Managed, non-interactive, invisible |
Key takeaways:
- Three products, three billing models. Polish compresses in place and costs nothing per image. Transformations resize on demand and bill per unique. Images stores the original and bills on storage, delivery, and transforms together. Picking the wrong one is a cost decision before it is an architecture decision.
- The transformation unique is the unit an attacker can drive. One source image and a loop over widths produces thousands of billable artifacts from requests that are individually cheap and individually well-formed. A closed preset map turns an unbounded space into four entries.
format=autois the one option worth setting on every variant. It negotiates AVIF or WebP from theAcceptheader at the edge, and it is the difference between shipping modern encodings and shipping JPEG to everyone.- Turnstile’s client callback is cosmetic. The token is evidence and the server’s
siteverifyexchange is the verdict. Disabling a submit button until a callback fires is a UI state, not a control. actionandcdatamake the token single-purpose. Without them a token minted for a newsletter form is a token for the login form. Both are echoed by Cloudflare and both must be compared server-side against what the rendering page expected.timeout-or-duplicateis a retry, not a rejection. It is almost always a slow form or a double click. Mapping it to 403 tells a human they are a robot; mapping it to a widget reset tells them to try again.- Neither product is a rate limiter. Turnstile answers whether a browser solved a challenge, and a credential-stuffing run can solve it correctly every time. The limiter bounds volume; Turnstile raises cost. Both, or neither.
Remember: The image side and the bot side fail in the same shape — each has a dimension that a caller can drive, and each is safe only when that dimension is bounded before the caller reaches it. On the image side the dimension is the option string, so it becomes a preset key and the preset map is the contract. On the bot side the dimension is the token, so it becomes a five-minute single-use value bound to one form and one session, and the exchange that proves it happens on the server. Everything else in the chapter follows from those two decisions: cache what the preset produces, sign what must stay private, and fail closed on the path that guards a login.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!