Merge pull request #190 from PotatoesMaster/htmx-middleware-vary-header

HtmxMiddleware: add Vary header to prevent caching issues
This commit is contained in:
bobf 2025-04-20 15:41:26 +01:00 committed by GitHub
commit 01d0862043
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -19,17 +19,21 @@ pub fn afterRequest(request: *jetzig.http.Request) !void {
/// If a redirect was issued during request processing, reset any response data, set response /// If a redirect was issued during request processing, reset any response data, set response
/// status to `200 OK` and replace the `Location` header with a `HX-Redirect` header. /// status to `200 OK` and replace the `Location` header with a `HX-Redirect` header.
/// Add Vary response header to prevent caching the page without layout for requests not coming
/// from htmx.
pub fn beforeResponse(request: *jetzig.http.Request, response: *jetzig.http.Response) !void { pub fn beforeResponse(request: *jetzig.http.Request, response: *jetzig.http.Response) !void {
switch (response.status_code) {
.moved_permanently, .found => {},
else => return,
}
if (request.headers.get("HX-Request") == null) return; if (request.headers.get("HX-Request") == null) return;
switch (response.status_code) {
.moved_permanently, .found => {
if (response.headers.get("Location")) |location| { if (response.headers.get("Location")) |location| {
response.status_code = .ok; response.status_code = .ok;
request.response_data.reset(); request.response_data.reset();
try response.headers.append("HX-Redirect", location); try response.headers.append("HX-Redirect", location);
} }
},
else => {
try response.headers.append("Vary", "HX-Request");
},
}
} }