Htmx fragment caching with Accept-Version
IF YOU'VE been developing htmx apps for a while, you might have tried to cache the HTML fragments generated by your server as htmx responses. Caching htmx fragments is the equivalent of caching JSON responses in a SPA. Eg, you might have a fragment response from GET /users/:id that renders a user detail view. You might want to cache this view to avoid expensive queries in the backend if you know the user details haven't changed. But when you start caching htmx fragments, a problem pops up: the style doesn't match the rest of your app. You might be rapidly iterating on the app and making adjustments (small or big) to its CSS. You quickly start to notice that annoyingly frequently, your user fragments are not updating to the latest style. Sure, you can do a hard reload and force the fragment to have the latest style. But surely there must be an easier way? Content negotiation Enter the version headers: Accept-Version : a request header set by your frontend to instruct the backend what version of a resource it wants Version : a response header set by your backend to inform the frontend what version of the resource it is serving. Basically, the backend and frontend have to agree on the version, otherwise they automatically do a hard reload. You can think of this as a lightweight form of content negotiation. Here's a pseudo-code for a backend middleware that shows the rules: if Accept-Version header not in request then continue with request pipeline else if Accept-Version header value = the expected version then continue with request pipeline else if request method is GET then respond with 200 OK empty body and a response header HX-Redirect: request target else continue with request pipeline finally add response header Version: expected version end The meat of this middleware is the redirect if the expected and actual versions don't match. This ensures that the response htmx fragment style can't drift out of sync with the rest of the app. Now, let's look at some of the d