Tags: web-dev platform

Cloudflare

Checked: 2026-10-29


A reverse proxy running on one global anycast network, sitting between visitors and your origin. Every product — content delivery network (CDN), web application firewall (WAF), bot defence, Rules, Workers — is a layer that request passes through on the way in, so the order of those layers explains almost every surprise.


§0 The one idea

Your domain resolves to Cloudflare, not to you.

Point the nameservers at Cloudflare, flip a record to “proxied”, and the public answer for www.example.com becomes a Cloudflare IP address. Every visitor’s request lands in the nearest Cloudflare data centre, gets terminated, inspected, possibly answered, and only then — maybe — forwarded to your server. Each product is a stage in that one pipeline, configured on the same proxy, rather than a separate box in your stack.

vs a normal stack: normally DNS points at a load balancer, and CDN, WAF and edge functions are three vendors bolted on in some order you chose. Here they’re one request path, run by one company, in a sequence Cloudflare chose — and the developer platform (Workers) is the same machines, so “edge code” and “the CDN” aren’t separate places.

NORMAL STACK                          BEHIND CLOUDFLARE

visitor                               visitor
  │ DNS → your IP                       │ DNS → Cloudflare anycast IP
  ▼                                     ▼
load balancer                         nearest Cloudflare data centre
  ▼                                     ├─ TLS terminated here
WAF appliance / vendor                  ├─ security · bots · rate limits
  ▼                                     ├─ Rules (redirects, rewrites, cache settings)
app servers                             ├─ Worker (your code, optional)
  ▼                                     ├─ cache
CDN only for /static                    ▼
                                      your origin — or no origin at all

Two consequences that follow from that alone:

  • Your origin stops seeing visitors. It sees Cloudflare. Client IP arrives in a header (CF-Connecting-IP), and anything that logged REMOTE_ADDR now logs Cloudflare
  • “Cloudflare-only” is possible. A Worker on a custom domain is the origin. Static assets, KV, D1 and R2 mean whole sites run with no server you own

At a glance

Unit of configThe zone — one domain. Plan (Free/Pro/Business/Enterprise) is per zone
Unit of codeThe Worker — belongs to the account, not a zone
Proxied vs DNS-onlyOrange cloud = traffic through Cloudflare. Grey = DNS answer only, nothing else applies
Proxyable recordsA, AAAA, CNAME only. MX, TXT etc. are always DNS-only
HTML cachingOff by default. Cached by extension list; HTML and JSON aren’t on it
Set-Cookie on a responseNot cached by default
Custom cache key on cookie/headerEnterprise only
RulesPage Rules being replaced by phased Rules — Cache, Configuration, Origin, Transform, Redirect
Worker runtimeV8 isolates, not containers. Web APIs (application programming interfaces), not Node by default
Worker vs cacheWorkers run before the cache
Config filewrangler.jsonc recommended for new projects; wrangler.toml still works
Static sitesWorkers with static assets. Pages still exists; Cloudflare says start new projects on Workers
Bot scoresGranular 1–99 score is Enterprise Bot Management only
R2 egressNot charged

The data model

Two trees hanging off one account, and the split between them causes most “where’s that setting” confusion.

Account
├─ Members · API tokens · billing
│
├─ Zone  example.com            ← plan lives here (Free/Pro/Business/Ent)
│   ├─ DNS records
│   │    ├─ www   CNAME  → origin.host      proxied (orange)
│   │    ├─ api   A      → 203.0.113.10     proxied (orange)
│   │    └─ mail  MX     → …                DNS-only (always)
│   ├─ SSL/TLS mode · edge certificates
│   ├─ Security — WAF custom rules · managed rules · rate limits · bots
│   ├─ Rules   — redirect · transform · origin · configuration · cache
│   ├─ Cache   — tiered cache · purge
│   └─ Worker routes   example.com/shop/*  → worker "ab-edge"
│
├─ Zone  example.co.uk  …
│
└─ Workers & storage            ← account-level, not per zone
    ├─ Worker "ab-edge"
    │    └─ bindings ──→ KV namespace "EXPERIMENTS"
    │                └─→ D1 database "assignments"
    │                └─→ R2 bucket "exports"
    │                └─→ Durable Object class "Counter"
    │                └─→ Queue "events"
    ├─ KV namespaces · D1 databases · R2 buckets · Queues
    └─ Ruleset-engine rules at account level (Enterprise)

Things to notice:

  • A Worker attaches to a zone only through a route or custom domain. The Worker itself is account-scoped, so one Worker can serve several zones
  • Storage is never “in” a Worker. The Worker gets a binding — a named handle injected at runtime. Rename the KV namespace and the code doesn’t change; rebind and the same code reads a different store
  • Plan features are per zone. A Pro zone and a Free zone in the same account have different WAF rulesets, rate-limit allowances and cache-key options

Zone setups

How a domain becomes a zone:

  • Full setup — Cloudflare is your authoritative DNS; you change nameservers at the registrar. The only option on Free and Pro
  • Partial (CNAME) setup — keep your existing DNS provider, CNAME individual subdomains to Cloudflare. Business and Enterprise
  • Subdomain setup — a delegated subdomain managed as its own zone. Enterprise

The full setup is why Cloudflare so often ends up as the company’s DNS by accident: someone wanted the CDN.


How traffic reaches Cloudflare

Proxied vs DNS-only

The orange cloud is the switch for everything else on the page.

record          status      DNS answer                  what applies
www  → origin   proxied     Cloudflare anycast IPs      everything below
www  → origin   DNS-only    your origin's real IP       nothing — DNS only
  • Proxied records answer with Cloudflare IPs, and the origin IP stays out of DNS. Their DNS time to live (TTL) is fixed at “Auto” — 300 seconds, not editable
  • DNS-only exposes the origin IP to anyone who queries the record. A grey-clouded direct.example.com pointing at the same server as the proxied www undoes the hiding, and it’s one of the commonest leaks
  • Proxying covers HTTP/HTTPS. Non-web traffic on other ports needs other products (Spectrum, Tunnel) [CHECK: exact list of proxied ports per plan]

Anycast

Anycast — the same IP addresses announced from every data centre at once, so internet routing delivers each visitor to a topologically close one. No geo-DNS decides where you go; BGP (Border Gateway Protocol, the routing protocol between networks) does.

same IP 104.x.x.x announced from:   LHR   AMS   FRA   JFK   SIN   …
visitor in Manchester  ── routes to ──→ LHR (or MAN)
visitor in Singapore   ── routes to ──→ SIN

Consequences: a visitor’s “edge location” is a routing outcome, not a choice; anything per-data-centre (Cache API, rate-limit counters) is per location, and a user can move between locations mid-session. See Edge Computing for why being near the user matters at all.

TLS at the edge

Cloudflare terminates TLS and HTTPS at its edge and opens a second connection to your origin. The SSL/TLS encryption mode controls the second leg:

ModeVisitor → CloudflareCloudflare → origin
OffHTTPHTTP
FlexibleHTTPSHTTP
FullHTTPSHTTPS, certificate not validated
Full (strict)HTTPSHTTPS, certificate validated (public certificate authority, or Cloudflare Origin CA)
Strict (SSL-only origin pull)anyalways HTTPS, validated

Automatic SSL/TLS is the default on migrated zones — it picks the most secure mode the origin supports and never downgrades.

Flexible is the trap. The padlock shows, but the origin leg is plain HTTP. Worse, an origin that redirects HTTP→HTTPS sees every request arrive as HTTP and redirects forever — the classic ERR_TOO_MANY_REDIRECTS after turning Cloudflare on [CHECK: the Flexible redirect-loop symptom isn’t stated on the current SSL modes page; mechanism is standard]. Full (strict) with an Origin CA certificate is the answer.


The request lifecycle

The Ruleset Engine runs a request through ordered phases. Each phase has at most one entry-point ruleset at account level and one at zone level; account runs first. Request phases, in order:

GET https://www.example.com/products/serum
  │
  ├─ DNS → Cloudflare anycast IP → nearest data centre
  ├─ TLS handshake (edge certificate)
  │
  │  REQUEST PHASES
  ├─  1  Single Redirects          http_request_dynamic_redirect
  ├─  2  URL normalisation         http_request_sanitize
  ├─  3  URL Rewrite Rules         http_request_transform
  ├─  4  Waiting Room
  ├─  5  API Shield (detect)
  ├─  6  Configuration Rules       http_config_settings
  ├─  7  Origin Rules              http_request_origin
  ├─  8  HTTP DDoS protection      ddos_l7
  ├─  9  WAF custom rules          http_request_firewall_custom   ← block / challenge
  ├─ 10  Rate limiting rules       http_ratelimit                 ← block
  ├─ 11  API Shield (mitigate)
  ├─ 12  WAF managed rules         http_request_firewall_managed  ← block
  ├─ 13  Super Bot Fight Mode      http_request_sbfm              ← challenge
  ├─ 14  Access check (Zero Trust)
  ├─ 15  Bulk Redirects            http_request_redirect
  ├─ 16  Managed Transforms
  ├─ 17  Request header transforms http_request_late_transform
  ├─ 18  Cache Rules               http_request_cache_settings    ← sets cache behaviour
  ├─ 19  Snippets                  http_request_snippets
  ├─ 20  Cloud Connector
  │
  ├─ WORKER (if a route matches)   ← your code; runs BEFORE cache
  │     └─ fetch(request) ──→ CACHE lookup ──hit──→ cached response
  │                               └──miss──→ ORIGIN
  │
  │  RESPONSE PHASES
  ├─  Custom Errors · Managed Transforms · response header transforms
  ├─  rate limiting (response-based) · Compression Rules
  ├─  Sensitive Data Detection · Logpush custom fields
  ▼
visitor

The phase list is Cloudflare’s published order. Where Workers sit is assembled from two documented facts — “Workers run before the cache”, and a Worker’s fetch() reads through its own zone’s cache — plus the security phases running first [CHECK: no single docs page places Workers in the phase list; confirm Worker runs after Snippets/Cloud Connector].

What the order means in practice:

  • Redirects happen before security. A Single Redirect fires before the WAF ever sees the request. Bulk Redirects come later, after security
  • Security runs before your Worker. A blocked or challenged request never invokes your code and never costs a Worker request
  • Cache Rules are settings, not the lookup. Phase 18 decides how the request will be cached; the actual cache lookup happens later, when the Worker (or the proxy, if there’s no Worker) fetches
  • A Worker’s response isn’t itself cached by the edge — the Worker always runs, and only its fetch() subrequests go through the cache. This is the property that makes edge experimentation work: cache the control HTML once, personalise per request
  • Account rules before zone rules, same phase

Rules — the replacement for Page Rules

Page Rules were one list of URL-pattern-plus-settings. They’re being migrated into phase-specific Rules; Cloudflare recommends the new Rules for anything new and migrates existing Page Rules with notice. Mapping:

Old Page Rule settingNow lives in
Forwarding URL, Always Use HTTPSRedirect Rules (Single Redirects)
Cache Level, Edge/Browser Cache TTL, Cache on Cookie, Custom Cache KeyCache Rules
Security Level, SSL, Rocket Loader, Polish…Configuration Rules
Host Header Override, Resolve OverrideOrigin Rules
True-Client-IP, geolocation headersManaged Transforms

Every Rule is an expression (Wireshark-style filter syntax) plus an action:

(http.request.uri.path wildcard "/products/*" and not http.cookie contains "cart=")
→ Cache Rule: eligible for cache, edge TTL 10m

Snippets sit between Rules and Workers: small JavaScript at phase 19, tight limits (5 ms execution, 2 MB memory, 32 KB package), Pro and above, no Free plan. For a header tweak or a cookie-based redirect they’re cheaper than a Worker.


Caching

CDN Caching and HTTP Caching cover the concepts. This is Cloudflare’s version of them.

What’s cached by default

By file extension, not MIME type (the Content-Type media type). Images, fonts, CSS, JS, PDFs, archives, media — yes. HTML and JSON — no. robots.txt is the one exception.

On top of the extension check, origin headers decide:

origin response                              cached?
Cache-Control: public, max-age=3600          yes, 1h
Cache-Control: private | no-store | no-cache  no
Cache-Control: max-age=0                     no
Set-Cookie: …                                no        ← the silent one
method is not GET                            no
no Cache-Control, status 200/206/301         yes, default edge TTL 120 min
no Cache-Control, status 404/410             yes, default edge TTL 3 min

The Set-Cookie row is where commerce sites lose their cache. A platform or tag that sets a session cookie on every response makes every response uncacheable, and nothing errors. The cf-cache-status response header (HIT, MISS, DYNAMIC, BYPASS, EXPIRED) is the first thing to check; DYNAMIC means “not eligible”, which usually means HTML or a cookie.

To cache HTML: a Cache Rule marking the path eligible for cache (the old “Cache Everything”), with an edge TTL — and a bypass condition for logged-in or cart cookies, or someone’s basket gets served to everyone.

The cache key

The cache key is what makes two requests “the same” for caching. Default: full URL (scheme, host, path, query string) plus the Origin header and a handful of method-override and forwarding headers.

same cached object?
/serum?utm_source=email         ┐
/serum?utm_source=ig            ┘ different keys — UTM (Urchin Tracking Module) params fragment the cache

with "ignore query string":     ┐
/serum?utm_source=email         │ one key
/serum?utm_source=ig            ┘ — but also /serum?variant=b collapses into it
Cache key optionPlans
Ignore query string · sort query string · cache by device type · cache deception armourAll
Include specific query params, headers, cookies, host, user featuresEnterprise
cf.cacheKey on a Worker fetch()Enterprise
Custom key via the Workers Cache API (caches.default)All, but per data centre

Why this matters for testing: below Enterprise you can’t tell the CDN “vary the cached page on the ab_bucket cookie”. Either the variant lives in the URL, or a Worker does the varying after the cache — see the A/B section.

Vary — Cache Rules gained configurable Vary support on all plans in 2026: the origin must send Vary, and the rule decides per header whether to normalise, pass through or bypass. Vary: * always bypasses [CHECK: whether Cookie is an allowed Vary header in Cache Rules].

Tiered cache

Without it, every data centre that misses goes to your origin. Tiered cache splits data centres into lower tiers (near visitors) and upper tiers (the only ones allowed to call the origin):

visitor → LHR (lower) ──miss──→ upper tier ──miss──→ origin
visitor → MAN (lower) ──miss──→ upper tier ──HIT──   (origin not touched)
  • Smart Tiered Cache — picks the single closest upper tier per origin from latency data. All plans
  • Generic Global, Regional, Custom topologies — Enterprise

Turn on Smart Tiered Cache; there’s rarely a reason not to. Cache API calls from a Worker don’t participate — the Cache API is local to one data centre. Use fetch() with cf cache options to get tiering.

Precedence

Worker fetch() cf options   >   Cache Rules   >   Page Rules

Worker overrides only apply with the right compatibility flag (request_cf_overrides_cache_rules for fetch). Without it, the Worker’s cache settings are silently ignored and Cache Rules win.


Security

WAF

The web application firewall (WAF) — rules matching requests and blocking, challenging, logging or skipping. Internal order: IP Access rules → custom rules → rate limiting rules → managed rules.

RulesetPlans
Free Managed RulesetAll, including Free
Cloudflare Managed RulesetPro and above
OWASP Core Ruleset (Open Worldwide Application Security Project)Pro and above
Leaked credentials detection[CHECK: plan availability]

Custom rules use the same expression language as every other Rule. The common legitimate one: a skip rule for your own uptime monitor and payment-provider webhooks, which managed rules and bot defences otherwise challenge.

Rate limiting

See Rate Limiting for the algorithms. Cloudflare’s shape:

PlanRulesCount byPeriod
Free1IP10 s
Pro2IPup to 1 min
Business5IP, IP with NAT supportup to 10 min
Enterprise~100IP, header, cookie, path, ASN, JA3/JA4, body fields…up to 65,535 s
  • NAT (network address translation) — many users behind one IP, e.g. an office or mobile carrier. IP-only counting rate-limits them collectively
  • ASN (autonomous system number) — the network an IP belongs to
  • JA3/JA4 — fingerprints of the TLS handshake, identifying the client software regardless of IP
  • Counters are per data centre, not global. A distributed attacker spread across locations each stays under the limit

Bots

Three tiers, and they behave differently enough to matter:

ProductPlanWhat it doesEscape hatch
Bot Fight ModeFreeChallenges requests matching known bot patterns, zone-wideNone — can’t be skipped by WAF rules; may challenge API and mobile-app traffic
Super Bot Fight ModePro, Business [CHECK: plan availability]Per-category actions (definitely automated, likely automated, verified bots)Skip rules supported
Bot ManagementEnterprise add-onBot score 1–99 per request (1 = certainly automated, 99 = certainly human), JA3/JA4, verified-bot flagFull rule control on cf.bot_management.score

Verified bots — known good crawlers (search engines, monitoring) that Cloudflare lets through by default.

Bot Fight Mode is the one to be careful with. It can’t be excepted, so it’s what silently breaks a webhook or a headless QA run.

Turnstile

Turnstile — Cloudflare’s CAPTCHA replacement (CAPTCHA: Completely Automated Public Turing test to tell Computers and Humans Apart). Runs non-interactive browser challenges; most visitors never see a puzzle. Works on any site — no proxying required.

browser                                  your server
widget runs challenges
  → token in hidden form field  ───────→ POST https://challenges.cloudflare.com/turnstile/v0/siteverify
                                           { secret, response: token }
                                         ← { success: true|false }
  • Server-side validation is mandatory. The widget alone protects nothing; a forged string passes the client
  • Token valid 300 seconds, single use
  • Modes: managed (shows a checkbox only if risky), non-interactive, invisible

The developer platform

Workers and the isolate model

A Worker is a JavaScript (or WebAssembly — WASM) module with a fetch handler, run by workerd, Cloudflare’s runtime built on V8 — JavaScript Runtimes. The unit of isolation is the V8 isolate, not a container.

CONTAINER / VM SERVERLESS              WORKERS

machine                                machine
├─ container A                         └─ one runtime process (V8)
│   ├─ OS userland                         ├─ isolate: your Worker
│   ├─ Node runtime                        ├─ isolate: someone else's
│   └─ your function                       ├─ isolate: someone else's
├─ container B                             └─ … hundreds to thousands
│   ├─ OS userland
│   ├─ Node runtime                     runtime paid for once per process;
│   └─ another function                 each isolate: own heap, own globals

What follows:

  • Cold starts nearly vanish. Cloudflare’s figure: isolates start roughly a hundred times faster than a Node process in a container, and use an order of magnitude less memory
  • Startup budget: the global scope must parse and run within 1 second
  • Global scope isn’t state. An isolate may serve several requests and keep globals between them — or be evicted at any moment, and the next request may land on a different machine. Never keep mutable state in globals; a module-level Map used as a cache works until it doesn’t
  • Web-platform APIs, not Node. fetch, Request, Response, URL, crypto.subtle, streams. Node built-ins only via the nodejs_compat compatibility flag [CHECK: current coverage of nodejs_compat]
  • Single-threaded per isolate, like the browser — the same The Event Loop model. CPU time is billed and limited; time spent awaiting I/O isn’t

Hydrogen’s Oxygen runtime is the same shape — see Reference - Hydrogen.

The smallest Worker

Complete and deployable:

export default {
  async fetch(request, env, ctx) {
    return new Response("hello from the edge");
  },
};

The three arguments are the whole model:

  • request — a standard Request, plus request.cf: country, city, ASN, TLS details, and (Enterprise Bot Management only) botManagement.score
  • env — the bindings: KV, D1, R2, secrets, vars. Nothing global; everything arrives here
  • ctx — ctx.waitUntil(promise) keeps work running after the response is sent (logging, analytics beacons) without delaying the visitor

A proxy Worker — sits on a route in front of an origin:

export default {
  async fetch(request, env, ctx) {
    const res = await fetch(request);               // → cache → origin
    const out = new Response(res.body, res);        // make headers mutable
    out.headers.set("x-served-by", "edge");
    ctx.waitUntil(env.EVENTS.send({ path: new URL(request.url).pathname })); // Queue, off the critical path
    return out;
  },
};

Routes vs custom domains vs workers.dev

AttachmentWorker’s roleUse
*.workers.devFree subdomainDevelopment, hobby. Not for production
Route — example.com/shop/*In front of an existing originEdge logic over a site you already run
Custom domainIs the originCloudflare-native apps

Bindings and the config file

Bindings are declared in config and injected as env.NAME. No connection strings, no credentials in code — the binding is the permission.

// wrangler.jsonc — recommended for new projects; wrangler.toml still supported
{
  "name": "ab-edge",
  "main": "src/index.js",
  "compatibility_date": "2026-10-29",   // pins runtime behaviour to this date
  "routes": [
    { "pattern": "www.example.com/*", "zone_name": "example.com" }
  ],
  "vars": { "EXPERIMENT_ID": "pdp-hero-2026-10" },     // plain config
  "kv_namespaces": [
    { "binding": "FLAGS", "id": "<KV_ID>" }            // env.FLAGS
  ],
  "d1_databases": [
    { "binding": "DB", "database_name": "assignments", "database_id": "<ID>" }
  ],
  "r2_buckets": [
    { "binding": "EXPORTS", "bucket_name": "exports" }
  ],
  "queues": {
    "producers": [{ "binding": "EVENTS", "queue": "events" }]
  },
  "durable_objects": {
    "bindings": [{ "name": "COUNTER", "class_name": "Counter" }]
  },
  "migrations": [
    { "tag": "v1", "new_sqlite_classes": ["Counter"] } // DO classes are declared via migrations
  ],
  "assets": { "directory": "./public", "binding": "ASSETS" }
}

compatibility_date is the runtime’s versioning mechanism: behaviour changes ship behind dates and flags, and your Worker keeps the behaviour of the date it names. Bumping it is an upgrade, and should be tested like one. Secrets go in via wrangler secret put, never in vars.

Storage — which one

Each is a different consistency and access model, and picking the wrong one is the usual architectural mistake.

What it isConsistencyGood forBad for
KVGlobal key-value, cached at the edgeEventual — other locations may take 60 s+ to see a writeConfig, flags, experiment definitions, redirects mapsCounters, anything written often per key
D1Managed SQLite databaseStrong per database [CHECK: read-replica consistency model]Relational app data, assignment logsHuge analytical scans
R2Object storage, compatible with Amazon S3’s APIStrongFiles, exports, images, backupsSmall hot lookups
Durable ObjectsA globally unique, single-threaded object with its own SQLite storageStrong — one instance, one threadCoordination: counters, rate limits, rooms, booking slotsEverything going through one object (it’s a bottleneck by design)
QueuesMessage queue between WorkersAt-least-once [CHECK: delivery guarantee]Offloading work from the request pathRequest/response
Cache APIProgrammatic cache, caches.defaultPer data centreCaching computed responsesAnything that must be shared globally
  • KV is eventually consistent — see Eventual Consistency. Default read cache 60 seconds, raisable via cacheTtl. Perfect for “which experiments are live”, wrong for “how many people are in arm B”
  • A Durable Object is addressed by name, so every request for "user:84213" reaches the same instance wherever it was created. Provisioned near where it’s first requested. Available on Free (SQLite backend only) and Paid
  • Queues — see Message Queues. The ctx.waitUntil + Queue pattern is how you send analytics events from the edge without adding latency

Pages vs Workers static assets

Pages was the static-site product (Git-connected builds, preview URLs, Pages Functions). Workers with static assets now covers the same ground: an assets directory served alongside a Worker, asset requests free. Cloudflare’s Pages docs carry a banner: start new projects with Workers. Pages isn’t deprecated; it’s just no longer where new features land. Durable Objects in particular are simpler from Workers.


Experimentation at the edge

The reason a CRO person cares. See Client-Side vs Server-Side Testing for the trade-off this sits inside — edge testing is server-side assignment without touching the origin.

The shape

request ── Worker ──────────────────────────────────────────────→ response
            │
            ├─ read cookie ab_pdp ─ present? → use it (sticky)
            │                     └ absent?  → hash(visitor id) → bucket
            ├─ fetch(request)  → cache HIT: one cached control HTML for everyone
            ├─ HTMLRewriter: apply variant B changes while streaming
            ├─ Set-Cookie: ab_pdp=B
            └─ Cache-Control: private on the way out (browser must not share it)

Why it beats client-side: no anti-flicker snippet, no Flicker and Flash of Original Content, nothing for an ad blocker to block, and the HTML arrives already in its variant — so Largest Contentful Paint (LCP) isn’t held hostage to a testing script.

Why the cache survives: the Worker runs before the cache, so the origin HTML is cached once and every visitor’s variant is produced by rewriting it. The cache key never needs the cookie — the thing that’s Enterprise-only.

HTMLRewriter

HTMLRewriter — a streaming HTML parser in the Workers runtime. Register CSS-selector handlers; it rewrites the response as it flows through, without buffering the whole document.

const COOKIE = "ab_pdp";
 
function bucket(id) {                       // deterministic: same id → same arm
  let h = 0;
  for (const c of id) h = (h * 31 + c.charCodeAt(0)) | 0;
  return Math.abs(h) % 100 < 50 ? "A" : "B"; // 50/50 split
}
 
export default {
  async fetch(request, env, ctx) {
    const res = await fetch(request);                       // cached control HTML
    if (!res.headers.get("content-type")?.includes("text/html")) return res;
 
    const cookies = request.headers.get("cookie") ?? "";
    let arm = cookies.match(/ab_pdp=(A|B)/)?.[1];           // sticky: honour existing
    const id = cookies.match(/vid=([\w-]+)/)?.[1] ?? crypto.randomUUID();
    arm ??= bucket(id + ":pdp-hero-2026-10");               // salt with experiment id
 
    let out = res;
    if (arm === "B") {
      out = new HTMLRewriter()
        .on("h1.pdp-title", { element(el) { el.setInnerContent("Clinically proven in 4 weeks"); } })
        .on("button.add-to-cart", { element(el) { el.setAttribute("class", "add-to-cart btn--large"); } })
        .on("head", { element(el) {                         // expose arm to analytics
          el.append(`<script>window.dataLayer=window.dataLayer||[];dataLayer.push({exp:"pdp-hero",arm:"B"})</script>`, { html: true });
        } })
        .transform(res);
    }
 
    out = new Response(out.body, out);
    out.headers.append("set-cookie", `${COOKIE}=${arm}; Path=/; Max-Age=2592000; Secure; SameSite=Lax`);
    out.headers.append("set-cookie", `vid=${id}; Path=/; Max-Age=31536000; Secure; SameSite=Lax`);
    out.headers.set("cache-control", "private, no-store");  // never let a browser/shared cache reuse a variant
    return out;
  },
};

What carries the trick:

  • Deterministic hashing, salted by experiment — the same principle as Assignment and Bucketing. A random draw per request with no cookie would re-assign on every cookieless hit
  • The cookie is set server-side, which matters for Browser Privacy Restrictions: Safari caps lifetimes on cookies written by JavaScript, not on first-party cookies set in an HTTP response [CHECK: current Safari Intelligent Tracking Prevention (ITP) treatment of CNAME-cloaked / IP-mismatched server-set cookies]. See Cookies
  • Handlers that throw truncate the page. HTMLRewriter halts on an exception; if streaming had started the visitor gets half a document. Wrap anything risky
  • Text arrives in chunks. A text handler may see one text node in several calls (lastInTextNode). Prefer element handlers and setInnerContent
  • Log the exposure — the dataLayer push, or a Queue event from the Worker, is what makes Experiment Assignment Tracking possible. Assignment without an exposure event is unanalysable

Ways it goes wrong

  • One arm served to everyone. Happens when the variant gets into the cache: the origin renders arm B (reading the cookie itself) on a path a Cache Rule makes cacheable, and the cache key doesn’t include the cookie. Either keep the origin variant-blind and vary only in the Worker, or bypass cache for that path. Check cf-cache-status and the arm cookie together in QA (quality assurance) — see Experiment QA
  • Bots get assigned. Crawlers without cookies get bucketed on every request, and if they reach your analytics, inflate one arm. Skip assignment for verified bots and filter in analysis — Bot and Internal Traffic, Sample Pollution. An arm imbalance from this shows up as Sample Ratio Mismatch
  • Redirect tests and SEO. Edge Split URL Tests with 302s are fine; caching the redirect isn’t
  • Cookie consent. An assignment cookie is still a cookie — Consent Management

Performance effects

Being behind Cloudflare changes the Core Web Vitals picture, mostly via Time to First Byte:

  • Cache HIT on HTML → TTFB is the distance to the nearest data centre. The biggest single gain available, and it’s off by default
  • Cache MISS / DYNAMIC → an extra hop. Edge TLS termination helps (shorter handshake round trips for the visitor), but a slow origin is still slow, now with Cloudflare in the middle
  • Worker on every HTML request → adds its CPU time and any awaited subrequests. An await on KV or an external API before fetch(request) sits directly in TTFB; fire it in parallel or waitUntil it
  • Tiered cache → fewer origin hits, lower miss latency for long-tail pages
  • Early Hints — Cloudflare can send 103 Early Hints with Link: rel=preload/preconnect headers learned from the origin’s earlier responses, so the browser starts fetching before the HTML [CHECK: exact mechanism and plan availability]
  • Rocket Loader defers all JavaScript, inline and external, until after render. It can help paint metrics and break scripts that assume execution order with the DOM; needs Content Security Policy changes. Test it, don’t assume
  • Zaraz — Cloudflare’s server-side tag manager, loading third-party tags from the edge. Same idea as Server-Side Tag Management [CHECK: current Zaraz status and pricing model]
  • Web Analytics — Cloudflare’s free cookieless real-user metrics. Useful as a second Real User Monitoring source, not a replacement [CHECK: still free, and which metrics it collects]

Bots and analytics

Cloudflare sees every request, including the ones your JS tag never fires on. Its analytics will always show more “visitors” than GA4 (Google Analytics 4) — bots, blocked tags, prefetches. Neither is wrong; they count different things. See Ad Blockers and Tracking Loss.


Limits and quirks

Workers limits

FreePaid
CPU time per request10 ms30 s default, configurable to 5 min
Wall-clock duration (HTTP)No limitNo limit
Memory per isolate128 MB128 MB
Subrequests per invocation5010,000 (raisable)
Worker size, uncompressed64 MiB64 MiB
Workers per account100500
Env vars + secrets per Worker64128
Requests per day100,000 (then error 1027)—
Cron / Queue consumer / DO alarm wall time15 min15 min

CPU time, not wall time. A Worker awaiting a slow origin for eight seconds uses almost no CPU. A Worker JSON-parsing a 5 MB payload can blow 10 ms on Free.

Quirks worth knowing

  • Origin sees Cloudflare IPs. Use CF-Connecting-IP and lock the origin firewall to Cloudflare’s published ranges, or attackers skip Cloudflare by hitting the origin directly
  • Grey-cloud leaks the origin. Historical DNS, a DNS-only subdomain, or a mail server on the same host all give the IP away
  • Purge by URL doesn’t reach Worker custom cache keys. Objects cached under cf.cacheKey can’t be purged by URL — use Cache Rules keys instead
  • Per-data-centre things: the Workers Cache API (“I cached it” means “I cached it in LHR”) and rate-limit counters
  • Silent no-ops: Worker cache overrides without the compatibility flag; Bot Fight Mode exceptions, which don’t exist
  • Rules order is fixed by phase, not by where you put the rule in the dashboard. A redirect “not firing” is often a WAF rule winning, or vice versa — Single Redirects run before security, Bulk Redirects after
  • Orange-to-orange — proxying a hostname that CNAMEs to another Cloudflare customer (many software-as-a-service platforms, Shopify included) behaves differently from a normal origin [CHECK: current orange-to-orange behaviour and Shopify’s guidance]
  • compatibility_date is a contract. Old dates keep old bugs; new dates change behaviour

Pricing model

No figures — those go to a quote. The axes:

  • Zone plan, per domain — Free / Pro / Business / Enterprise. Gates WAF rulesets, rate-limit rules, cache-key options, Snippets, bot tier, partial DNS setup
  • Enterprise add-ons — Bot Management, Advanced Rate Limiting, custom tiered topologies, priced by contract
  • Workers Paid, per account — a monthly minimum, then:
    • Workers: requests + CPU milliseconds. Duration not billed. Static asset requests free
    • KV: reads, writes, deletes, lists, storage
    • D1: rows read, rows written, storage
    • R2: storage, Class A (mutating) and Class B (read) operations. Egress free
    • Durable Objects: requests, wall-clock duration (GB-seconds), plus storage rows/units
    • Queues: operations, per 64 KB chunk
  • No platform egress charge on Workers Paid; Containers are the exception

The cost surprise is rarely bandwidth — it’s CPU-heavy Workers on every request, or D1 queries that scan rather than seek and get billed per row read.