Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(hobby): serve versioned posthog-js script paths as unversioned (#122371)

Paul D'Ambraaa11316c95a7
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 402bdc79214a..1050eca2a44d 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -41,7 +41,7 @@ from statshog.defaults.django import statsd
from posthog.api.shared import UserBasicSerializer
from posthog.clickhouse.client.execute import clickhouse_query_counter
from posthog.clickhouse.query_tagging import QueryCounter, get_query_tag_value, reset_query_tags, tag_queries
-from posthog.cloud_utils import is_cloud, is_dev_mode
+from posthog.cloud_utils import is_cloud, is_dev_mode, is_hobby
from posthog.constants import AUTH_BACKEND_KEYS
from posthog.event_usage import get_event_source, get_mcp_properties, sanitize_header_value
from posthog.geoip import get_geoip_properties
@@ -1227,6 +1227,26 @@ class AutoLogoutImpersonateMiddleware:
return self.get_response(request)
+class UnversionedStaticPathMiddleware:
+ """Serves /static/<version>/<file> as /static/<file>.
+
+ A posthog-js client with `strict_script_versioning` asks for its extension scripts under
+ a version folder. Cloud serves those from a versioned CDN bucket. A self-hosted instance
+ holds one build of each script, so any version gets that build, as an unversioned request
+ does. Only self-hosted instances rewrite, so a request on cloud never changes.
+ """
+
+ VERSIONED_STATIC_PATH = re.compile(r"^/static/\d+\.\d+\.\d+(?:-[\w.]+)?/")
+
+ def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:
+ self.get_response = get_response
+
+ def __call__(self, request: HttpRequest) -> HttpResponse:
+ if is_hobby():
+ request.path_info = self.VERSIONED_STATIC_PATH.sub("/static/", request.path_info, count=1)
+ return self.get_response(request)
+
+
class Fix204Middleware:
"""
Remove the 'Content-Type', 'Content-Length' and 'X-Content-Type-Options: nosniff' headers and set content to empty string for HTTP 204 response (and only those).
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 6ed69906f979..cb29bba4e254 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -10,6 +10,7 @@ from corsheaders.defaults import default_headers
from whitenoise.compress import Compressor
from posthog.openapi.enum_names import ChoicesEnumNameOverrides
+from posthog.run_mode import derive_run_mode
from posthog.scopes import get_scope_descriptions
from posthog.settings.base_variables import BASE_DIR, CLOUD_DEPLOYMENT, DEBUG, TEST
from posthog.settings.utils import (
@@ -179,6 +180,10 @@ INSTALLED_APPS = [
"django_admin_inline_paginator",
]
+_UNVERSIONED_STATIC_MIDDLEWARE = (
+ ["posthog.middleware.UnversionedStaticPathMiddleware"] if derive_run_mode(CLOUD_DEPLOYMENT, DEBUG).is_hobby else []
+)
+
MIDDLEWARE = [
"django_prometheus.middleware.PrometheusBeforeMiddleware",
"posthog.gzip_middleware.ScopedGZipMiddleware",
@@ -196,6 +201,7 @@ MIDDLEWARE = [
"posthog.health.healthcheck_middleware",
"posthog.middleware.ShortCircuitMiddleware",
"posthog.middleware.AllowIPMiddleware",
+ *_UNVERSIONED_STATIC_MIDDLEWARE, # Must precede WhiteNoise — it reads the path this rewrites
"whitenoise.middleware.WhiteNoiseMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"posthog.middleware.OAuthCorsPreflightMiddleware", # Must precede CorsMiddleware — echoes custom headers on OAuth preflights
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index db5ef5169584..b68c828476a4 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -38,6 +38,7 @@ from posthog.middleware import (
Fix204Middleware,
ManagedProxyClientIPMiddleware,
SignedClientIPOutcome,
+ UnversionedStaticPathMiddleware,
per_request_logging_context_middleware,
user_logging_context_middleware,
)
@@ -46,7 +47,8 @@ from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_invite import OrganizationInvite
from posthog.models.team import Team
from posthog.models.user import User
-from posthog.settings import SITE_URL
+from posthog.run_mode import derive_run_mode
+from posthog.settings import SITE_URL, base_variables
from posthog.utils import get_ip_address, get_trusted_client_ip
from products.access_control.backend.models.access_control import AccessControl
@@ -418,6 +420,59 @@ class TestFix204Middleware(SimpleTestCase):
assert "Content-Length" not in response.headers
+class TestUnversionedStaticPathMiddleware(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("versioned_script", "/static/1.438.12/posthog-recorder.js", "/static/posthog-recorder.js"),
+ ("prerelease_version", "/static/1.438.12-beta.1/array.js", "/static/array.js"),
+ ("nested_file", "/static/1.438.12/icons/a.png", "/static/icons/a.png"),
+ ("unversioned_script", "/static/posthog-recorder.js", "/static/posthog-recorder.js"),
+ ("hashed_asset_folder", "/static/chunks/1.2.js", "/static/chunks/1.2.js"),
+ ("version_outside_static", "/api/1.438.12/foo", "/api/1.438.12/foo"),
+ ]
+ )
+ @override_settings(CLOUD_DEPLOYMENT=None, DEBUG=False)
+ def test_rewrites_only_versioned_static_paths(self, _name: str, path: str, expected_path: str) -> None:
+ seen_paths: list[str] = []
+
+ def get_response(request: HttpRequest) -> HttpResponse:
+ seen_paths.append(request.path_info)
+ return HttpResponse()
+
+ UnversionedStaticPathMiddleware(get_response)(RequestFactory().get(path))
+
+ assert seen_paths == [expected_path]
+
+ @parameterized.expand(
+ [
+ ("us_cloud", "US", False),
+ ("eu_cloud", "EU", False),
+ ("cloud_dev", "DEV", False),
+ ("local_development", None, True),
+ ]
+ )
+ def test_never_rewrites_outside_hobby(self, _name: str, cloud_deployment: str | None, debug: bool) -> None:
+ seen_paths: list[str] = []
+
+ def get_response(request: HttpRequest) -> HttpResponse:
+ seen_paths.append(request.path_info)
+ return HttpResponse()
+
+ with override_settings(CLOUD_DEPLOYMENT=cloud_deployment, DEBUG=debug):
+ UnversionedStaticPathMiddleware(get_response)(RequestFactory().get("/static/1.438.12/array.js"))
+
+ assert seen_paths == ["/static/1.438.12/array.js"]
+
+ def test_registered_only_in_hobby_and_before_whitenoise(self) -> None:
+ middleware = list(settings.MIDDLEWARE)
+ name = "posthog.middleware.UnversionedStaticPathMiddleware"
+ registered_expected = derive_run_mode(base_variables.CLOUD_DEPLOYMENT, base_variables.DEBUG).is_hobby
+
+ assert (name in middleware) == registered_expected
+ if registered_expected:
+ assert middleware.index(name) < middleware.index("whitenoise.middleware.WhiteNoiseMiddleware")
+
+
class TestAutoProjectMiddleware(APIBaseTest):
# How many queries are made in the base app
# On Cloud there's an additional multi_tenancy_organizationbilling query