Cloudflare

Purge Cloudflare's cache when content changes with @cms/cloudflare, so cached reads and pages can live for hours.

@cms/cloudflare is a plugin that purges Cloudflare’s cache when editors change content. It purges by the cache tags the engine puts on published reads, so a publish evicts every cached API read that holds the document, and every page your site tagged with what it read. With it, the cache window can go from seconds to hours and a publish still shows right away.

          pnpm add @cms/cloudflare
        
          // cms.config.tsx
import { cloudflare } from "@cms/cloudflare";
import { config } from "@cms/config";

export default config({
  // ...
  cacheTags: { prefix: "site:" },
  apiCache: { sMaxAge: 3600 },
  plugins: [
    cloudflare({
      zoneId: "023e105f4ecef8ad9ca31a8372d0c353",
      apiToken: process.env.CLOUDFLARE_API_TOKEN,
    }),
  ],
});
        

Set up the zone’s cache rule first: see Deployment → Cloudflare setup.

Options

Option Type Description
zoneId string The zone the CMS is served from, and the site, if its pages should be purged too. On the zone’s Overview page in the Cloudflare dashboard.
apiToken string | undefined An API token with the zone’s Cache Purge permission (see The API token). Read it from process.env: cms.config is bundled into the admin, so a token written in the file would ship with it. cms start refuses to boot without it; cms dev boots without it, and needs it only with enabledInDev. Don’t wrap it in requiredEnv(), which would make cms dev refuse to boot too.
purge "tags" | "everything" "tags" (default) purges the tags of what changed. "everything" purges the whole zone instead, once per burst of changes.
repurgeAfterMs number Purges again this many milliseconds later. Default 10000; 0 purges once. See The second purge.
enabledInDev boolean Purge from cms dev too. Default false.
name string The instance name. Default: "cloudflare".

Purging by tag needs cacheTags in the config: without it no read carries a tag, and the engine refuses to boot. The plugin reads the tag prefix from cacheTags.prefix, so the two always match.

The API token

Create it under Manage Account → Account API Tokens, not under My Profile: an account-owned token keeps working when the person who made it leaves, while a profile token dies with that person’s access.

  • Permission: Cache & Performance → Cache Purge, with Specified Domains set to the zone.
  • Client IP filtering: leave it off. A host whose egress IPs aren’t fixed (Fly, most container platforms) gets every call refused.

The permission can’t be narrowed to tags: it allows every kind of purge, purge-everything included. What keeps the CMS to tags is purge: "tags" in the config, and the purge-everything route is admin-only. Treat the token as able to empty the zone.

cms start refuses to boot when zoneId or apiToken is empty. If both come from the environment, set the token in the same deploy as the zone id, or before it. On Fly, fly secrets set --stage stages secrets without restarting, so both ship in one deploy.

What a change purges

Change Purged tags
Publish, unpublish <prefix>d:<id> and <prefix>e:<entity>
Delete <prefix>d:<id> and <prefix>e:<entity>. A response that resolved or referenced the document carries its d: tag, so it goes too. Also <prefix>e:<referrer> for every entity or global with a relation (nested ones included) to the deleted document’s entity: the delete clears their references without saving them, which can change their lists.
Save, on an entity or global without drafts <prefix>d:<id> and <prefix>e:<entity>
Create, on an entity without drafts <prefix>e:<entity>: its lists change
Draft save or draft create, on an entity with drafts Nothing. The publish purges.

Purging e:<entity> evicts every list, find and search that read the entity, and every read that resolved into it. Built-in entities (users and assets) aren’t watched.

Batching and failures

The plugin calls Cloudflare a second after the first change of a burst, with every change made in that second, so a burst (a bulk publish, an import) becomes a few calls. The second runs from the first change, not from the last: a burst that never pauses still purges every second, rather than waiting for a quiet moment that may not come. Each call carries up to 100 tags, Cloudflare’s limit per purge request. Cloudflare limits purge requests per account: 5 a minute on Free (in bursts of up to 25), 5 a second on Pro, 10 on Business. Every burst costs two calls, the first purge and the second, so the Free plan fits about two separate publishes a minute, shared by every project and environment on the account. A busy Free-plan project can reach that. purge: "everything" sends one call per burst, but on a zone shared with another environment it empties that environment’s cache too (see Staging and production on one zone); a paid plan or a zone of its own is the better fix there.

A purge never fails the editor’s save: it runs after the write commits. A failed call is logged once at error and reported once through the engine’s error reporting, as the plugin’s (a call can carry several editors’ changes), so with @cms/sentry it reaches Sentry as an error. A 429 is retried once, after the Retry-After delay Cloudflare sends (12 seconds without one). Refused again, it is the plan’s limit doing its job rather than a broken purge, so it is logged at warn and not reported: with @cms/sentry it lands in Sentry Logs without raising an issue. A revoked token (401/403), a wrong zone, a Cloudflare outage (5xx) or a network error is still reported, and still raises one. The warn line names what was not purged and the call that recovers:

          Cloudflare rate-limited a purge of 2 tags on zone <zone-id> (first); not purged: stg:d:k3j9x2,stg:e:pages. POST /api/plugins/cloudflare/purge-everything clears the zone.
        

With purge: "everything", the refused call already was a whole-zone purge, so the line says to retry purge-everything once the rate limit clears instead.

On shutdown, the plugin waits for the calls already on their way and sends the purges still waiting at once, second purges included: their timers would never fire. A 429 met while shutting down is logged at warn the same way, not retried, so the shutdown doesn’t wait out its Retry-After.

The second purge

A page your site was rendering while an editor published may have read the old content. If it reaches Cloudflare after the purge, it is cached with the old content for the whole window. The plugin therefore sends every purge a second time, repurgeAfterMs after the first one settled (a retried 429 included), so the two never overlap. Keep it longer than your slowest page render. On shutdown, a second purge still waiting is sent right away rather than dropped.

Purging everything by hand

POST /api/plugins/cloudflare/purge-everything purges the whole zone right away, for after an incident or a schema change. Only admins may call it. It answers { data: { purged: true } }, { data: { purged: false } } in cms dev (where it only logs), or 502 with Cloudflare’s message when the purge fails (a 429 still refused after its retry included, logged at warn).

Purging after a deploy

A deploy changes no content, so nothing purges then. But when its migration changes what the API answers (a new or renamed field, a backfill), every cached read keeps the old shape until its window runs out, and a site deployed next reads responses without the fields its new code expects. POST /api/plugins/cloudflare/purge-entities closes that gap: it purges the <prefix>e:<entity> tag of every entity in the config, the built-in ones (users and assets) and the plugins’ included. Every published read carries its entities’ e: tags, so this evicts every cached read of the environment, and every page your site tagged with them, and nothing else on the zone: another environment’s prefix, asset files and images stay cached.

Call it from the deploy pipeline once the CMS deploy has finished, and before the site deploys. Never from the release command (Fly’s release_command, where cms migration apply runs): the old machines keep answering until the rolling deploy ends, and would store old-shape reads again. Calling it on every deploy is cheap, so the pipeline needn’t know whether the shape changed.

          curl --fail-with-body -X POST \
  -H "Authorization: Bearer $CMS_ADMIN_API_KEY" \
  https://cms.example.com/api/plugins/cloudflare/purge-entities
        

CMS_ADMIN_API_KEY is a key for the admin role (cms key create --name "Deploy purge"): the route is admin-only, and CI needs no Cloudflare token of its own. The tags go out right away, in calls of at most 100, with no second purge, and the route answers once Cloudflare has answered:

Status When
200 { data: { purged: true, tags: 42 } }: the tag count it purged. purged: false in cms dev, where it only logs.
429 Cloudflare still rate-limited the call after one retry. The response carries Cloudflare’s Retry-After: wait that long and call again.
502 Any other failure, with Cloudflare’s message.
409 The plugin runs with purge: "everything", so there are no tags to purge: call purge-everything instead.

In development

cms dev never calls Cloudflare: the plugin logs the purges it would make instead, so local work can’t purge a live zone. Set enabledInDev: true to purge from cms dev, for instance against a staging zone.

Staging and production on one zone

Two environments served from one domain (cms.staging.example.com and cms.example.com) share one zone, and a purge by tag evicts that tag wherever it is cached in the zone. Give each environment its own cacheTags.prefix, read from the environment:

          cacheTags: { prefix: requiredEnv("CACHE_TAG_PREFIX") }, // "stg:" on staging, "prd:" on production
        

Read it through requiredEnv() (see Runtime variables in cms.config): an unset prefix would otherwise boot with no prefix at all, and that environment’s tags would no longer be its own.

Staging’s publishes, and its purge-entities route, then purge only stg: tags. Two things stay shared: the purge rate limit (see Batching and failures), and purge: "everything" or the purge-everything route, which empty the zone for both environments.

Checking that purges work

What the logs show

Each call Cloudflare accepts is logged at info:

          Cloudflare purged 3 tags on zone 023e105f4ecef8ad9ca31a8372d0c353 (first, 148 ms): stg:d:k3j9x2,stg:e:pages,stg:e:navigation
        

The round is first, repurge, manual (the purge-everything route) or entities (the purge-entities route), and a call with more than five tags lists the first five and +N more. A publish therefore logs two lines, repurgeAfterMs apart. These lines go to the server’s output only (fly logs, for instance): @cms/sentry forwards warn and above, so Sentry never sees a successful purge. It sees a failed one as an error, and a rate-limited one as a warn log.

A Cloudflare call takes about 150 ms, and a published change is fresh at the edge about 1.5 seconds after the publish: the one-second batch window, the call, and Cloudflare spreading the purge to its locations.

By hand

  1. GET a shared API read anonymously until cf-cache-status reads HIT. Use a plain GET, not curl -I: the Cache Rule applies to GET, so a HEAD always reads DYNAMIC.
  2. Purge one of its tags in the dashboard: Caching → Custom Purge → Tag.
  3. GET it again. A MISS while age is still below sMaxAge shows the purge evicted it, not expiry.

age can go backwards between two reads, and a single MISS right after a HIT is normal: a Cloudflare location runs several cache servers, each with its own copy.

A smoke check

An end-to-end script that publishes and watches the edge catches what a hand check misses (a page that isn’t tagged, a missing entity tag on an empty list). What made one reliable:

  • Read the edge through the public host, and the origin past Cloudflare. Cloudflare strips Cache-Tag, so to see a response’s tags, read the origin with curl --connect-to cms.example.com:443:<origin-host>:443 https://cms.example.com/…: the request keeps the public hostname, so a redirect to the canonical host doesn’t bounce it.
  • Start every run cold. Add a query parameter unique to the run (?smoke=<run id>); it’s part of the cache key, so nothing earlier is cached under it.
  • Warm every target before changing anything, then change, then read.
  • Wait repurgeAfterMs plus about 3 seconds between checks. The second purge of one check otherwise lands during the next check’s warm-up and evicts it, and the next check reads a MISS that has nothing to do with its own change.
  • Include a 404. Publishing a document at a path whose lookup was cached as a 404 replaces it within the same 1.5 seconds: the empty lookup carried e:<entity>.

Two zones

The site’s pages are purged by the same call as the CMS’s reads when both are served from one zone, so one instance covers both. A second instance is needed only when the site sits on a different zone from the CMS. Register each under its own name:

          plugins: [
  cloudflare({ zoneId: CMS_ZONE, apiToken: process.env.CLOUDFLARE_API_TOKEN }),
  cloudflare({ name: "cloudflare-site", zoneId: SITE_ZONE, apiToken: process.env.CLOUDFLARE_SITE_TOKEN }),
],
        

Previous

Blocks

Next

Links