"""Middleware.""" from __future__ import annotations import logging import pathlib from django.conf import settings from whitenoise.middleware import WhiteNoiseMiddleware # type: ignore[import-untyped] logger = logging.getLogger(__name__) IMMUTABLE_ROOT = settings.FRONTEND_DIR / "dist" / "assets" class ImmutableReactWhiteNoiseMiddleware(WhiteNoiseMiddleware): # type: ignore[misc] """ Custom middleware to handle a Vite application. Custom middleware that extends WhiteNoiseMiddleware to better handle immutable static files in a React application. It overrides the immutable_file_test method to mark files within a specified IMMUTABLE_ROOT directory as immutable, allowing for more aggressive caching by browsers and CDNs. If a file is not within IMMUTABLE_ROOT, it falls back to the default WhiteNoise logic. """ def immutable_file_test(self, path: str, url: str) -> bool: """Return True if the path is hashed by whitenoise or in IMMUTABLE_ROOT.""" return pathlib.Path(path).is_relative_to( IMMUTABLE_ROOT, ) or super().immutable_file_test( path, url, )