Skip to content

Commit

Permalink
Ensure HTML pages vary on HX-Request
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
friedelwolff committed Aug 16, 2024
1 parent 2148b4d commit 0118920
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
1 change: 1 addition & 0 deletions app/app/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"simple_history.middleware.HistoryRequestMiddleware",
"django_htmx.middleware.HtmxMiddleware",
"general.middleware.ExtraVaryMiddleware",
]

if DEBUG and DEBUG_TOOLBAR:
Expand Down
17 changes: 17 additions & 0 deletions app/general/middleware.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 0118920

Please sign in to comment.