---
title: 'Cloudflare HTML Cache, Purged on Publish'
date: '2026-11-10'
description: pablofr.com's pages sit in Cloudflare's cache for a week and still change the second I publish. Half the work was making them cacheable at all.
author: Pablo Fernandez
tags:
  - Cloudflare
  - Caching
  - Next.js
  - Performance
  - Infrastructure
source: 'https://www.pablofr.com/blog/cloudflare-html-cache-purged-on-publish'
---
Telling a CDN to keep your HTML for seven days sounds like a way to serve last week's blog. That's the setting this site runs with, and a post I publish shows up everywhere within seconds. The week is never reached: every change throws the whole cache away, so the TTL only decides how long a page survives when nothing happens, which on a blog is most of the time.

Getting there took three things, and the Cloudflare rule was the smallest of them. Before any of it, every page on pablofr.com paid the trip from Cloudflare's edge to my server in Germany, and most pages couldn't have been cached anyway, because Next.js had quietly decided they were all dynamic.

## Every page paid the trip to Germany

The site runs on [one VPS](/blog/pfrctl-infrastructure-as-code) in Falkenstein, behind Cloudflare. Cloudflare doesn't cache HTML by default, only static files, so every page view crossed from the nearest Cloudflare data centre to that machine and back. From Spain that's not far. From a US data centre it's an ocean.

I measured both paths this morning from my Mac in Spain, over home fibre, through Cloudflare's Madrid data centre: 15 requests each, time to first byte as curl reports it. A HIT is the page served from Madrid. A MISS is forced with a random query string, so Cloudflare has to fetch it from the origin, which already has the page rendered:

| Page | Edge HIT, median | Origin MISS, median | MISS range |
| --- | --- | --- | --- |
| `/` | 83 ms | 184 ms | 109 to 455 ms |
| `/blog/a-model-that-decides-for-you` | 74 ms | 179 ms | 112 to 481 ms |

A hundred milliseconds from Madrid. The difference that actually triggered this was further away: an [Ahrefs](https://ahrefs.com) crawl flagged pages as slow, because its crawler fetched from the US and every request went all the way to Germany.

## The page that read your cookies

The first surprise was that there was nothing to cache. Next.js renders a page statically only if nothing in it depends on the request, and one line in the API client depended on the request for every single page. The axios interceptor that attaches the logged-in user's token looked for it in the cookies when running on the server:

```typescript:api.services.ts
// 2. Check for token in server environment (Next.js)
try {
    const { cookies } = await import("next/headers");
    const cookieStore = await cookies();
    const token = cookieStore.get("access_token")?.value;
    if (token) {
        config.headers.Authorization = `Bearer ${token}`;
    }
} catch (e) {
    // Not in a Next.js server context or cookies() not available
}
```

[`cookies()`](https://nextjs.org/docs/app/api-reference/functions/cookies) is a dynamic API: calling it tells Next the response depends on who's asking. So any server component that fetched through this client, which was every public page, became dynamic, and dynamic pages are sent with headers that tell every cache not to keep them. The build's route table had zero static pages.

The public pages never needed a token. Posts, projects and the site config come from public endpoints that only return published content. So the public pages stopped using the shared client and got their own fetch: no cookies, and cached by Next with tags:

```typescript:posts.server.ts
const res = await fetch(
  `${getPublicApiBaseUrl()}/v1/posts/${encodeURIComponent(slug)}`,
  { next: { revalidate: REVALIDATE_SECONDS, tags: ["posts", `post:${slug}`] } },
);
```

Both conditions matter, and missing either one keeps a page dynamic: the fetch must not read cookies, and it must be cacheable (an uncached fetch is dynamic too). With that, the home, each post and the projects page render once and are served from Next's cache for an hour, and Next sends them with `cache-control: s-maxage=3600, stale-while-revalidate=31532400`, which a CDN can work with.

## A week, because an hour wasn't enough

The [Cache Rule](https://developers.cloudflare.com/cache/how-to/cache-rules/) started modest: make the home, `/blog*`, `/projects`, `/downloads` and the feeds eligible for caching, and respect the hour Next asks for. It didn't fix the crawler. Cloudflare has hundreds of data centres, and each keeps its own copy, so with an hour of TTL a page that nobody in Ashburn had read in the last hour was a MISS in Ashburn, and a crawler visiting each page once is exactly that nobody.

Two changes fixed it. [Smart Tiered Cache](https://developers.cloudflare.com/cache/how-to/tiered-cache/) puts one upper tier between the edge and my server, close to the origin: a MISS in Ashburn asks that tier first, and only the tier asks Germany. And the edge TTL went from respecting Next's hour to [ignoring it](https://developers.cloudflare.com/cache/how-to/cache-rules/settings/) for seven days, with error pages kept five minutes and server errors never cached, so a bad deploy can't stick.

Overriding the origin has a side effect I didn't plan. `/blog`, the post list, reads the tag and page filters from the query string, so Next sends it as `no-store`. The rule overrides that too: `/blog` comes back as a HIT with `cache-control: private, no-cache, no-store`, which looks like a bug in the headers. It's fine, because the query string is part of the cache key (so `/blog?tag=AI` is its own entry) and the purge below clears the list with everything else, but it means the headers no longer tell you what the edge does. The one exclusion that matters is in the rule itself: a request whose `Accept` asks for `text/markdown` is never cached, so a [URL that speaks Markdown](/blog/a-url-that-speaks-markdown) still reaches the origin and gets its redirect to the `.md`. Cloudflare reports it as `DYNAMIC`.

## Throwing the whole cache away

A week of cache is only safe if a change reaches the edge right away, and that's the part in code. When I publish a post, the core API's MDX watcher syncs it to Postgres and then calls the web app's revalidation endpoint with the tags that changed (`posts`, `post:<slug>`). Next drops those entries from its cache. Then core-api purges Cloudflare:

```
  publish / edit / deploy
           │
           ▼
  ┌─────────────────┐   POST /api/revalidate    ┌──────────────┐
  │    core-api     │ ────────────────────────▶ │  web (Next)  │
  └────────┬────────┘   tags: posts, post:x     └──────────────┘
           │ wait 2 s for more changes
           ▼
  ┌─────────────────┐
  │   Cloudflare    │   purge host www.pablofr.com
  └────────┬────────┘
           │ next visitor: MISS, then HIT for a week
           ▼
        any page
```

*A change reaches the edge in two steps: Next drops its cached data by tag, then Cloudflare drops every page of the host, two seconds after the last change.*

```typescript:web-revalidate.lib.ts
const PURGE_DEBOUNCE_MS = 2000;
let purgeTimer: ReturnType<typeof setTimeout> | null = null;

function scheduleEdgePurge() {
  if (!process.env.CF_ZONE_ID || !process.env.CF_PURGE_TOKEN) return;
  if (purgeTimer) clearTimeout(purgeTimer);
  purgeTimer = setTimeout(() => {
    purgeTimer = null;
    void purgeEdgeCache();
  }, PURGE_DEBOUNCE_MS);
}
```

The purge is [by hostname](https://developers.cloudflare.com/cache/how-to/purge-cache/purge-by-hostname/), not by URL. A new post doesn't only change its own page: it changes the home, the post list, the feeds, the sitemap and the RSC payloads behind each of them, and working out that list for every kind of change is the kind of cleverness that ends with one stale page nobody notices for a week. The site is small enough that refilling the whole edge costs nothing, so the whole host goes. The two-second debounce is there because an MDX sync of ten posts, or a burst of edits in the admin, would otherwise fire ten purges, and Cloudflare [rate-limits](https://developers.cloudflare.com/fundamentals/api/reference/limits/) its API. The token can only purge, nothing else. A deploy does the same purge at the end, since a new image can change every page's layout.

## The first visitor after a purge

A purge moves the cost somewhere. Right after one, every page is a MISS, and right after a deploy the origin is cold too: Next hasn't rendered anything since the container started. The deploy's notes record what that first visitor got: about 1.9 seconds to first byte for a page nobody had rendered yet, long enough for Ahrefs to report a slow server response to AI crawlers.

The natural fix, warming Cloudflare by requesting every page after the purge, doesn't work from a CI runner: Cloudflare turns datacenter IPs away with a 403. So the deploy warms the next layer down. It runs a short script inside the web container that reads the sitemap and requests every page from `127.0.0.1`, four at a time. The edge still starts empty, but its first MISS for each page now costs the trip to an origin that already has the page, the 180 ms in the table above, not a cold render.

## Where it can still go wrong

The purge is best effort, on purpose: if Cloudflare refuses it or times out, core-api logs it and moves on, and publishing never fails because of the cache. The cost is that a failed purge leaves pages up to a week stale instead of an hour. That's the trade of the long TTL, and the fix is to look for "edge purge" in core-api's logs when a page doesn't change.

The quieter failure is in the first line of that function. Without `CF_ZONE_ID` and `CF_PURGE_TOKEN`, it returns without a word, so purging is simply off. And adding a variable to the server's `.env` isn't enough to turn it on: Watchtower, which rolls out new images, recreates a container with the environment of the one it replaces, so a variable added later never reaches it. It needs a `docker compose up -d --force-recreate` of that service, once.

And there are days with no edge cache at all. When Spanish ISPs block Cloudflare's IP ranges during football matches, the site [switches its DNS to point straight at the VPS](/blog/a-site-that-survives-laliga-blocks) until the block ends, and for those hours every request goes to the origin. The warm origin is what makes that bearable.

What I like about the result is that the long TTL and the instant updates aren't in tension: they're the same decision, seen from two sides. A week of cache is only reasonable because every change purges everything, and purging everything is only cheap because the cache is so rarely cold. Most of the work wasn't Cloudflare. It was one `cookies()` call in a shared client, which made a static blog render like a dashboard.
