Statamic static caching vs per-user markup
On this page
I had an addon that adds a small bit of markup to every page for logged-in users. The obvious implementation is response middleware: let the page render, then inject the HTML before it goes out. It worked locally. It failed on the client's site in two different ways, and both came from static caching.
Why middleware cannot do it
With full-measure static caching, Statamic writes complete HTML pages to public/static/ and nginx serves them directly. On a cache hit, PHP does not run. Your middleware does not run. Nothing you registered runs.
It is worse on the miss. Statamic pushes its StaticCaching\Middleware\Cache last onto the statamic.web group, so any middleware an addon registers on web wraps it. Your injection happens inside the first, uncached render, the cache middleware writes the result to disk, and from then on every visitor, logged in or not, gets the logged-in markup. That is a silent leak of exactly the content you were trying to gate.
I also tried pushing a nocache region from that outer middleware. The cache middleware calls $this->nocache->write() on its way out, so a region pushed after it is never persisted.
What works
Listen for Statamic\Events\ResponseCreated. It is dispatched from DataResponse while the page is still being built, before caching. In the listener:
if (Cache::isBeingUsedOnCurrentRoute()) {
$placeholder = app(Session::class)
->pushRegion('{{ my_addon:badge }}', [], 'antlers.html')
->placeholder();
// inject $placeholder into the response body
} else {
// inject the rendered markup directly
}
The important detail is that you push the tag, not the rendered output. The region stores Antlers source and re-renders per request through Statamic's nocache endpoint, so the auth check happens for each visitor. In a template the equivalent is wrapping the output in {{ nocache }}. A client-side fetch is the other honest option when the markup is small.
One debugging note that cost me an hour: nocache sessions are keyed by the full URL, scheme and host included. $session->setUrl('/')->restore() returns zero regions and looks like a failure when it is not.
The absolute-URL gotcha
Static HTML bakes in whatever APP_URL was when the page was generated. After a server move, one site served every stylesheet from http:// on an https:// page: mixed content, no styles. The .env was correct, the cached config was correct, and none of it mattered because nginx was serving a file written on migration day. php please static:clear fixed it. If your deploy script skips builds on the CMS's own [BOT] commits, which mine do, that clear will not run on its own after a domain or scheme change. Run it by hand.
The short version: on a statically cached site, treat the cached file as the real output. If something must differ per user, it has to go through nocache or the browser, and anything that depends on the URL needs a cache clear when the URL changes.