: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf: render the app context as a json script block (#106306)
Paul D'Ambra34739804d95b
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex ab25d3adca2f..c59fabebb333 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -323,7 +323,7 @@ class TestOAuthAPI(APIBaseTest):# The serialized bootstrap, not the view's own template context: `_build_template_context`# forwards only an allowlist of caller-provided keys, and a key it omits never reaches the# frontend.- resolution = json.loads(response.context["posthog_app_context"])["oauth_scope_resolution"]+ resolution = response.context["posthog_app_context"]["oauth_scope_resolution"]self.assertEqual(resolution["scopes"], sorted({"insight:read", "canvas:read"} | ALWAYS_ALLOWED_SCOPES))self.assertTrue(resolution["was_defaulted"])@@ -342,7 +342,7 @@ class TestOAuthAPI(APIBaseTest):def applies() -> bool:response = self.client.get(self.base_authorization_url)self.assertEqual(response.status_code, status.HTTP_200_OK)- return json.loads(response.context["posthog_app_context"])["oauth_consent_access_controls_apply"]+ return response.context["posthog_app_context"]["oauth_consent_access_controls_apply"]access_control_feature = [{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}]self.assertFalse(applies())diff --git a/posthog/templates/head.html b/posthog/templates/head.htmlindex 09295ad64d1d..0993635ae6bf 100644--- a/posthog/templates/head.html+++ b/posthog/templates/head.html@@ -25,6 +25,10 @@<meta name="apple-mobile-web-app-title" content="PostHog"><meta name="application-name" content="PostHog">{% if not opt_out_capture and js_posthog_api_key %}+ {{ posthog_bootstrap|page_json_script:"posthog-user-identity-with-flags" }}+ {% if js_posthog_identity_distinct_id and js_posthog_identity_claims %}+ {{ js_posthog_identity_claims|page_json_script:"posthog-identity-claims" }}+ {% endif %}<script nonce="{{ request.csp_nonce }}">window.JS_POSTHOG_API_KEY = "{{ js_posthog_api_key|escapejs }}";window.JS_POSTHOG_HOST = "{{ js_posthog_host|escapejs }}";@@ -33,14 +37,14 @@}window.JS_POSTHOG_UI_HOST = "{{ js_posthog_ui_host|escapejs }}";window.JS_POSTHOG_SELF_CAPTURE = {{self_capture | yesno:"true,false" }};- window.POSTHOG_USER_IDENTITY_WITH_FLAGS = JSON.parse("{{ posthog_bootstrap | escapejs }}")+ window.POSTHOG_USER_IDENTITY_WITH_FLAGS = JSON.parse(document.getElementById('posthog-user-identity-with-flags').textContent)window.IMPERSONATED_SESSION = {{is_impersonated_session | yesno:"true,false"}};window.POSTHOG_JS_UUID_VERSION = "{{posthog_js_uuid_version}}";{% if js_posthog_identity_distinct_id %}window.JS_POSTHOG_IDENTITY_DISTINCT_ID = "{{ js_posthog_identity_distinct_id|escapejs }}";window.JS_POSTHOG_IDENTITY_HASH = "{{ js_posthog_identity_hash|escapejs }}";{% if js_posthog_identity_claims %}- window.JS_POSTHOG_IDENTITY_CLAIMS = JSON.parse("{{ js_posthog_identity_claims|escapejs }}");+ window.JS_POSTHOG_IDENTITY_CLAIMS = JSON.parse(document.getElementById('posthog-identity-claims').textContent);{% endif %}{% endif %}</script>@@ -48,9 +52,9 @@{% if stripe_public_key %}<script nonce="{{ request.csp_nonce }}">window.STRIPE_PUBLIC_KEY = '{{ stripe_public_key | escapejs }}';</script>{% endif %}+{{ posthog_app_context|page_json_script:"posthog-app-context" }}<script nonce="{{ request.csp_nonce }}" id='posthog-app-user-preload'>- {# nosemgrep: generic.html-templates.security.var-in-script-tag.var-in-script-tag #}- window.POSTHOG_APP_CONTEXT = JSON.parse("{{ posthog_app_context | escapejs }}");+ window.POSTHOG_APP_CONTEXT = JSON.parse(document.getElementById('posthog-app-context').textContent);{# Inject the expected location of JS bundle, #}{# use to allow the location of the bundle to be set at runtime, #}{# e.g. for PostHog Cloud we serve the frontend JS from a CDN #}diff --git a/posthog/templatetags/posthog_filters.py b/posthog/templatetags/posthog_filters.pyindex dc4c219ac1db..ed486ef584ca 100644--- a/posthog/templatetags/posthog_filters.py+++ b/posthog/templatetags/posthog_filters.py@@ -6,7 +6,11 @@from typing import Optional, Unionfrom django import template+from django.core.serializers.json import DjangoJSONEncoder+from django.utils.html import json_script+from django.utils.safestring import SafeString+from posthog.exceptions_capture import capture_exceptionfrom posthog.utils import compact_numberregister = template.Library()@@ -28,3 +32,18 @@ def intcomma(value: Optional[Number]) -> str:return "-"return f"{int(value):,}"+++class TolerantJSONEncoder(DjangoJSONEncoder):+ # One unserializable value writes null instead of failing every page render.+ def default(self, o: object) -> object:+ try:+ return super().default(o)+ except TypeError:+ capture_exception(TypeError(f"unserializable {type(o).__name__} in page context"))+ return None+++def page_json_script(value: object, element_id: str) -> SafeString:+ return json_script(value, element_id, encoder=TolerantJSONEncoder)diff --git a/posthog/test/test_get_context_for_template.py b/posthog/test/test_get_context_for_template.pyindex aa811abb1d82..a9f1f1c4b586 100644--- a/posthog/test/test_get_context_for_template.py+++ b/posthog/test/test_get_context_for_template.py@@ -44,8 +44,8 @@ class TestGetContextForTemplate(APIBaseTest):"js_posthog_host": "","js_url": "http://localhost:8234","opt_out_capture": False,- "posthog_app_context": '{"persisted_feature_flags": ["the_persisted_flags"], "anonymous": false}',- "posthog_bootstrap": "{}",+ "posthog_app_context": {"persisted_feature_flags": ["the_persisted_flags"], "anonymous": False},+ "posthog_bootstrap": {},"posthog_js_uuid_version": "v7","region": None,"self_capture": True,@@ -77,7 +77,7 @@ class TestGetContextForTemplate(APIBaseTest):actual = get_context_for_template("layout", request)- app_context = json.loads(actual["posthog_app_context"])+ app_context = actual["posthog_app_context"]assert app_context["homepage"] == (stored_homepage or None)def test_bootstraps_project_tags_into_app_context(self):@@ -91,7 +91,7 @@ class TestGetContextForTemplate(APIBaseTest):actual = get_context_for_template("layout", request)- app_context = json.loads(actual["posthog_app_context"])+ app_context = actual["posthog_app_context"]assert sorted(app_context["current_project"]["tags"]) == ["eu-region", "production"]@parameterized.expand(@@ -138,7 +138,7 @@ class TestGetContextForTemplate(APIBaseTest):assert ("js_posthog_identity_claims" in context) is expects_claimif expects_claim:- claims = json.loads(context["js_posthog_identity_claims"])+ claims = context["js_posthog_identity_claims"]assert claims["email"]["value"] == self.user.email.lower()current_time = int(time.time())assert current_time < claims["email"]["expires_at"] <= current_time + IDENTITY_CLAIM_MAX_AGE_SECONDSdiff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex 93ec156c03df..ef65c4228f7e 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -411,7 +411,7 @@ class TestAutoProjectMiddleware(APIBaseTest):self.user.current_organization = self.organizationdef app_context(self, response) -> dict:- return json.loads(response.context["posthog_app_context"])+ return response.context["posthog_app_context"]@override_settings(PERSON_ON_EVENTS_V2_OVERRIDE=False)def test_project_switched_when_accessing_dashboard_of_another_accessible_team(self):diff --git a/posthog/test/test_stable_chunks.py b/posthog/test/test_stable_chunks.pyindex 2807535a5025..8b94f5deb4d6 100644--- a/posthog/test/test_stable_chunks.py+++ b/posthog/test/test_stable_chunks.py@@ -187,6 +187,6 @@ class TestStableChunksChoiceSurvivesTheRequest(APIBaseTest):context = get_context_for_template("index.html", request)assert context.get("stable_chunks", False) == expect_stable- assert json.loads(context["posthog_bootstrap"]).get("featureFlags") == flags+ assert context["posthog_bootstrap"].get("featureFlags") == flagsget_all_flags.assert_called_once()assert get_all_flags.call_args.kwargs["only_evaluate_locally"] is Truediff --git a/posthog/test/test_templatetags.py b/posthog/test/test_templatetags.pyindex 3ef80154db6d..29a9ddc63621 100644--- a/posthog/test/test_templatetags.py+++ b/posthog/test/test_templatetags.py@@ -1,4 +1,10 @@-from django.test import TestCase+import json+from uuid import UUID++from unittest.mock import patch++from django.template import Context, Template+from django.test import SimpleTestCase, TestCasefrom posthog.templatetags.posthog_filters import compact_number@@ -10,3 +16,15 @@ class TestTemplateTags(TestCase):self.assertEqual(compact_number(5392), "5.39K")self.assertEqual(compact_number(2833102), "2.83M")self.assertEqual(compact_number(8283310234), "8.28B")+++class TestPageJsonScript(SimpleTestCase):+ @patch("posthog.templatetags.posthog_filters.capture_exception")+ def test_unserializable_value_renders_null_and_is_reported(self, mock_capture) -> None:+ uuid = UUID("00000000-0000-4000-8000-000000000001")+ html = Template('{{ value|page_json_script:"x" }}').render(Context({"value": {"bad": {1}, "id": uuid}}))++ body = html.split(">", 1)[1].rsplit("</script>", 1)[0]+ self.assertEqual(json.loads(body), {"bad": None, "id": str(uuid)})+ mock_capture.assert_called_once()+ self.assertIn("set", str(mock_capture.call_args.args[0]))diff --git a/posthog/utils.py b/posthog/utils.pyindex 023be8161a1a..e6dddf117d9c 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -703,9 +703,7 @@ def _build_template_context(if caller_key in context:posthog_app_context[caller_key] = context.pop(caller_key)- # JSON dumps here since there may be objects like Queries- # that are not serializable by Django's JSON serializer- context["posthog_app_context"] = json.dumps(posthog_app_context, default=json_uuid_convert)+ context["posthog_app_context"] = posthog_app_contextif posthog_distinct_id:groups = {}@@ -736,7 +734,7 @@ def _build_template_context(# This allows immediate flag availability on the frontend, atleast for flags# that don't depend on any person properties. To get these flags, add person properties to the# `get_all_flags` call above.- context["posthog_bootstrap"] = json.dumps(posthog_bootstrap)+ context["posthog_bootstrap"] = posthog_bootstrapcontext["posthog_js_uuid_version"] = settings.POSTHOG_JS_UUID_VERSION@@ -792,21 +790,19 @@ def _build_template_context(if user_email:canonical_email = canonicalize_claim_value("email", user_email)expires_at = int(time.time()) + IDENTITY_CLAIM_MAX_AGE_SECONDS- context["js_posthog_identity_claims"] = json.dumps(- {- "email": {- "value": canonical_email,- "expires_at": expires_at,- "hash": compute_identity_claim_hash(- posthog_distinct_id,- "email",- canonical_email,- support_secret,- expires_at=expires_at,- ),- }+ context["js_posthog_identity_claims"] = {+ "email": {+ "value": canonical_email,+ "expires_at": expires_at,+ "hash": compute_identity_claim_hash(+ posthog_distinct_id,+ "email",+ canonical_email,+ support_secret,+ expires_at=expires_at,+ ),}- )+ }return context@@ -1145,11 +1141,6 @@ def get_frontend_apps(team_id: int) -> dict[int, dict[str, Any]]:return frontend_apps-def json_uuid_convert(o):- if isinstance(o, uuid.UUID):- return str(o)--def friendly_time(seconds: float):minutes, seconds = divmod(seconds, 60.0)hours, minutes = divmod(minutes, 60.0)diff --git a/products/access_control/backend/tests/test_access_control.py b/products/access_control/backend/tests/test_access_control.pyindex f33485dd2351..05d71e19183a 100644--- a/products/access_control/backend/tests/test_access_control.py+++ b/products/access_control/backend/tests/test_access_control.py@@ -1464,7 +1464,7 @@ class TestAccessControlProjectFiltering(BaseAccessControlTest):render_template("index.html", request=mock_request, context={})# Get the context passed to the template- return json.loads(mock_template.render.call_args[0][0]["posthog_app_context"])+ return mock_template.render.call_args[0][0]["posthog_app_context"]def test_default_lists_all_projects(self):assert len(self.client.get("/api/projects").json()["results"]) == 3