From 0118920733a8083dd2688c72c599b7223833a85e Mon Sep 17 00:00:00 2001 From: Friedel Wolff Date: Fri, 16 Aug 2024 22:15:04 +0200 Subject: [PATCH] Ensure HTML pages vary on HX-Request This fixes the problem with a partial page showing on browser restore, or for example with Firefox plugin "Auto Tab Discard" if a tab is restored. It will also be required if "real" caching is implemented. --- app/app/settings.py | 1 + app/general/middleware.py | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 app/general/middleware.py diff --git a/app/app/settings.py b/app/app/settings.py index adfddeff..496d6863 100644 --- a/app/app/settings.py +++ b/app/app/settings.py @@ -77,6 +77,7 @@ "django.middleware.clickjacking.XFrameOptionsMiddleware", "simple_history.middleware.HistoryRequestMiddleware", "django_htmx.middleware.HtmxMiddleware", + "general.middleware.ExtraVaryMiddleware", ] if DEBUG and DEBUG_TOOLBAR: diff --git a/app/general/middleware.py b/app/general/middleware.py new file mode 100644 index 00000000..589ed26e --- /dev/null +++ b/app/general/middleware.py @@ -0,0 +1,17 @@ +from django.utils.cache import patch_vary_headers + + +class ExtraVaryMiddleware: + """Ensure HTML pages vary on HX-Request + + This is needed so that incomplete responses based on base_htmx.html are not + reused as full-page responses, for example on browser restore of a page.""" + + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + response = self.get_response(request) + if "text/html" in response.headers["Content-Type"]: + patch_vary_headers(response, ["HX-Request"]) + return response