DEV Community

静亭雅苑
静亭雅苑

Posted on

HTML-Only Cloudflare Purge After a Self-Hosted Static Deploy

HTML-Only Cloudflare Purge After a Self-Hosted Static Deploy

A self-hosted static blog has a cache problem that a GitHub Pages site does not: the origin is yours, the edge is Cloudflare, and a deploy can leave visitors looking at the previous HTML while the new files are already on disk.

The naive fix is “Purge Everything” after every release. It works, but it also throws away the cached JavaScript, CSS, and images. The next visitor pays for a cold asset cache, and the performance work you did to avoid a cold start is undone by the deploy process.

On wuhuajin.com, the release script purges only HTML URLs after a successful health check. Static assets keep their long cache. The browser is told not to cache HTML; Cloudflare keeps a five-minute edge copy as a fallback.

This article describes the setup, the least-privilege token, the dry-run path, and the failure behavior that keeps a cache purge from becoming a deploy blocker.


The cache shape

The site uses three different cache policies:

Resource Browser cache Edge cache Why
HTML no-store / bypass 5 minutes Content changes per deploy; browser must not hold old pages
Hashed JS/CSS Long-lived Long-lived Filenames or ?v= hashes change when content changes
Images Long-lived Long-lived Usually immutable enough for a personal site

The HTML policy is the important one. A five-minute edge TTL means a new deploy can take up to five minutes to appear on every edge node. That is acceptable for a blog, but not for a correction or a broken page. A purge after a successful deploy closes that window without touching assets.

The first attempt at the rule left the browser TTL at its default. Cloudflare returned cache-control: max-age=14400, must-revalidate, which would let a browser show a four-hour-old HTML page. The corrected rule sets the browser TTL to bypass and returns must-revalidate, no-store. The edge still caches for five minutes.

That distinction is the whole design: short edge cache, no browser cache, long asset cache, purge HTML after deploy.


The token should be able to purge and nothing else

The purge script needs two permissions:

  • Zone → Cache Purge → Purge;
  • Zone → Zone → Zone Read (to resolve the zone ID from the zone name).

If you do not want to grant Zone Read, set CF_ZONE_ID explicitly and grant only Cache Purge.

Create a custom token scoped to the specific zone:

Zone Resources:
  Include → Specific zone → example.com
Enter fullscreen mode Exit fullscreen mode

Do not use a global API key. Do not put the token in the repository. The production environment file is the right place:

CF_API_TOKEN=your-scoped-token
CF_ZONE_NAME=example.com
# Optional if the token has no Zone Read permission
CF_ZONE_ID=your-zone-id
Enter fullscreen mode Exit fullscreen mode

Keep the file readable only by the deploy user:

chmod 600 /srv/site-api/secrets.conf
Enter fullscreen mode Exit fullscreen mode

The script reads the token from the environment, not from a command-line argument. A token in a shell history or a process list is a leak waiting to happen.


Run a dry run before the first real purge

The purge script has a dry-run mode that lists the HTML URLs without calling the API:

node scripts/deploy/purge-cloudflare-html.cjs --dry-run
Enter fullscreen mode Exit fullscreen mode

A healthy output looks like:

[purge] HTML URLs: 44
[purge] dry-run; first 8:
  https://example.com/
  https://example.com/about.html
  ...
Enter fullscreen mode Exit fullscreen mode

The count should match the number of HTML files the deploy produced. If it is zero, the file discovery is wrong. If it includes /src/js/app.js, the filter is too broad.

The real run is a POST to the Cloudflare purge endpoint with the URL list. Cloudflare accepts a limited number of URLs per request, so the script batches them:

[purge] submitted 30/44
[purge] submitted 44/44
[purge] done: 44 HTML URLs purged
Enter fullscreen mode Exit fullscreen mode

Batching is not a performance optimization; it is an API constraint. A single request with too many URLs fails, and a failed purge after a deploy is exactly the moment you do not want a partial result.


Purge after health checks, not before

The release order matters:

  1. Build the static output.
  2. Upload or sync it to the origin.
  3. Run health checks against the origin or a bypassed host.
  4. Purge the HTML URLs.
  5. Verify a cache miss followed by a cache hit.

Purging before the new files are live can create a short window where the edge fetches the old HTML and caches it for another five minutes. Purging after the health check means the edge repopulates from the new origin.

A simple verification is:

curl -sI https://example.com/ | grep -i 'cf-cache-status\|cache-control'
Enter fullscreen mode Exit fullscreen mode

After a purge, the first request should be MISS; the second should be HIT with a small age. The browser header should remain no-store or must-revalidate, not a long max-age.

That check catches two different mistakes: purging the wrong URL set, and accidentally giving the browser a long HTML cache.


Failure behavior: the deploy should not fail because the cache failed

A purge is an optimization, not a transaction. If Cloudflare is slow or the token expires, the new files are already live. The site should not roll back a successful deploy because the cache API returned an error.

The script follows three rules:

  • No token: skip the purge and log that the five-minute TTL is the fallback.
  • API failure: log the error, leave the deploy successful, and let the TTL expire.
  • No Node.js on the server: skip the step, same fallback.

There is also an explicit --no-purge flag for a deploy where the cache should be left alone, such as an origin-only maintenance change.

The important part is the log. A silent skip looks like a successful purge. The release output should say “skipped” or “failed, falling back to TTL” so the operator knows whether the edge was actually cleared.


Do not purge everything

“Purge Everything” is tempting because it is one button and it always works. It also invalidates the asset cache:

  • the hashed CSS bundle is cold again;
  • the JavaScript bundle is cold again;
  • images are cold again;
  • the next visitor pays for all of it.

On a small site, that may look harmless. On a mobile connection, it is the difference between a first screen that renders in one second and one that waits for a cold CSS round trip. The HTML purge is narrower because only HTML changes per deploy; hashed assets are content-addressed and should not be invalidated by a content release.

If the site does not use content hashes, the asset URLs may change in place. In that case, a targeted purge of the changed asset URLs is better than a global purge, but the real fix is to add a version hash.


The release integration

The release wrapper calls the purge script only after the deploy and health check succeed. A simplified sequence is:

./deploy.sh
node scripts/deploy/purge-cloudflare-html.cjs
Enter fullscreen mode Exit fullscreen mode

In the actual release script, the purge is a labeled step:

== Release finish: purge Cloudflare HTML cache ==
[purge] HTML URLs: 44
[purge] submitted 30/44
[purge] submitted 44/44
[purge] done: 44 HTML URLs purged
   Cloudflare HTML cache purged
Enter fullscreen mode Exit fullscreen mode

The next deploy uses the same path. There is no manual dashboard step, and no “remember to purge” note in a runbook.


What changed in practice

Before the HTML edge cache and targeted purge, the same build produced TTFB samples from roughly 0.56 to 1.64 seconds depending on cache state. After the cache rule and purge path, Lighthouse document response settled around 190–230ms on cache hits, and the homepage moved into the 98–99 Performance range.

That is not only a cache win. It is a reduction in variance. A page that sometimes takes 1.6 seconds to start is hard to optimize with confidence; a page that usually starts in 200ms is easier to measure.

The tradeoff is a five-minute staleness window if the purge fails. For a personal blog, that is acceptable. For a site with a correction workflow or a time-sensitive announcement, use a shorter TTL or a deploy hook that blocks on purge success.


Checklist

  • [ ] HTML edge TTL is short and explicit.
  • [ ] Browser TTL bypasses HTML cache.
  • [ ] Asset URLs are hashed or versioned.
  • [ ] Cloudflare token is scoped to one zone and can only purge cache.
  • [ ] Token lives in the production environment file, not the repository.
  • [ ] Purge script has a dry-run mode and a URL count.
  • [ ] Purge runs after upload and health checks.
  • [ ] Purge failure does not roll back a successful deploy.
  • [ ] --no-purge exists for maintenance releases.
  • [ ] Verification checks cf-cache-status and cache-control.

The goal is not “always purge.” The goal is to invalidate exactly the layer that changed, and to leave everything else warm.


This article describes the release cache strategy on wuhuajin.com, a self-hosted static blog behind Cloudflare. Domain names, paths, and tokens in the examples are placeholders; the production values are kept out of the public repository.


Originally published on wuhuajin.com.

Top comments (0)