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.

feat(frontend): fetch the user's app context in parallel behind a flag (#124338)

Paul D'Ambra7743090119cb
diff --git a/frontend/src/index.tsx b/frontend/src/index.tsx
index fe053105b8f8..4baccde410dd 100644
--- a/frontend/src/index.tsx
+++ b/frontend/src/index.tsx
@@ -6,26 +6,29 @@ import { Suspense, lazy } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { markBootPhase } from 'lib/utils/bootTiming'
+import { applyDeferredAppContext } from 'lib/utils/deferredAppContext'
import { retryBootImport } from 'lib/utils/retryImport'
import { RootErrorBoundary } from './RootErrorBoundary'
import { ChunkLoadErrorBoundary } from './scenes/ChunkLoadErrorBoundary'
-markBootPhase('entry')
+markBootPhase('entry', { deferred_app_context: !!window.POSTHOG_APP_CONTEXT_REQUEST })
type AppModules = [typeof import('scenes/App'), typeof import('scenes/bootApp')]
let appModulesPromise: Promise<AppModules> | undefined
function loadAppModules(): Promise<AppModules> {
- return (appModulesPromise ??= Promise.all([
- retryBootImport(() => import('scenes/App')),
- retryBootImport(() => import('scenes/bootApp')),
- ]).then((modules) => {
- // Marked here, not in the lazy() factory: React calls the factory only after the CSS gate in boot().
- markBootPhase('app_modules_loaded')
- return modules
- }))
+ // Some app modules read the app context when they load. The modulepreload links still fetch their code meanwhile.
+ return (appModulesPromise ??= applyDeferredAppContext()
+ .then(() =>
+ Promise.all([retryBootImport(() => import('scenes/App')), retryBootImport(() => import('scenes/bootApp'))])
+ )
+ .then((modules) => {
+ // Marked here, not in the lazy() factory: React calls the factory only after the CSS gate in boot().
+ markBootPhase('app_modules_loaded')
+ return modules
+ }))
}
// Lazy-load App so the entry chunk stays minimal: the entire transitive dependency
diff --git a/frontend/src/lib/utils/bootTiming.ts b/frontend/src/lib/utils/bootTiming.ts
index e964742bc3f8..b25cb14dc2aa 100644
--- a/frontend/src/lib/utils/bootTiming.ts
+++ b/frontend/src/lib/utils/bootTiming.ts
@@ -4,6 +4,7 @@ const SAMPLE_RATE = 0.05
export type BootPhase =
| 'entry'
+ | 'app_context_loaded'
| 'app_modules_loaded'
| 'css_ready'
| 'app_booted'
@@ -15,6 +16,7 @@ export type BootPhase =
export interface BootContext {
scene?: string
logged_in?: boolean
+ deferred_app_context?: boolean
}
const phaseTimes: Partial<Record<BootPhase, number>> = {}
diff --git a/frontend/src/lib/utils/deferredAppContext.test.ts b/frontend/src/lib/utils/deferredAppContext.test.ts
new file mode 100644
index 000000000000..01833069d4b6
--- /dev/null
+++ b/frontend/src/lib/utils/deferredAppContext.test.ts
@@ -0,0 +1,43 @@
+import { AppContext, UserType } from '~/types'
+
+import { applyDeferredAppContext, inlineAppContextUrl } from './deferredAppContext'
+
+describe('deferredAppContext', () => {
+ afterEach(() => {
+ delete window.POSTHOG_APP_CONTEXT_REQUEST
+ })
+
+ it('adds the user data and flags to what the page rendered', async () => {
+ window.POSTHOG_APP_CONTEXT = { anonymous: false, deferred: true, current_user: null } as unknown as AppContext
+ window.POSTHOG_USER_IDENTITY_WITH_FLAGS = { distinctID: 'page-distinct-id' }
+ window.POSTHOG_APP_CONTEXT_REQUEST = Promise.resolve({
+ app_context: { current_user: { distinct_id: 'user-1' } as UserType },
+ feature_flags: { 'some-flag': true },
+ })
+
+ await applyDeferredAppContext()
+
+ expect(window.POSTHOG_APP_CONTEXT).toEqual({
+ anonymous: false,
+ deferred: true,
+ current_user: { distinct_id: 'user-1' },
+ })
+ expect(window.POSTHOG_USER_IDENTITY_WITH_FLAGS).toEqual({
+ distinctID: 'page-distinct-id',
+ featureFlags: { 'some-flag': true },
+ })
+ })
+
+ it.each([
+ [
+ 'https://us.posthog.com/project/1/insights?a=1#tab',
+ 'https://us.posthog.com/project/1/insights?a=1&deferred_app_context=0#tab',
+ ],
+ [
+ 'https://us.posthog.com/project/1?deferred_app_context=1',
+ 'https://us.posthog.com/project/1?deferred_app_context=0',
+ ],
+ ])('reloads %s with the user data inline', (href, expected) => {
+ expect(inlineAppContextUrl(href)).toEqual(expected)
+ })
+})
diff --git a/frontend/src/lib/utils/deferredAppContext.ts b/frontend/src/lib/utils/deferredAppContext.ts
new file mode 100644
index 000000000000..0c6bd7cd08ca
--- /dev/null
+++ b/frontend/src/lib/utils/deferredAppContext.ts
@@ -0,0 +1,49 @@
+import type { AppContext } from '~/types'
+
+import { markBootPhase } from './bootTiming'
+
+// pinned: query param read by `should_defer_app_context` in posthog/utils.py
+const DEFERRED_APP_CONTEXT_PARAM = 'deferred_app_context'
+
+interface DeferredAppContext {
+ app_context: Partial<AppContext>
+ feature_flags: Record<string, boolean | string> | null
+}
+
+declare global {
+ interface Window {
+ /** Set by the page when it leaves the user's data out of the app context. See head.html. */
+ POSTHOG_APP_CONTEXT_REQUEST?: Promise<DeferredAppContext>
+ }
+}
+
+export function inlineAppContextUrl(href: string): string {
+ const url = new URL(href)
+ url.searchParams.set(DEFERRED_APP_CONTEXT_PARAM, '0')
+ return url.toString()
+}
+
+/**
+ * Adds the user's data to the app context when the page left it out. Code that reads the app context
+ * when its module loads must not load before this resolves.
+ */
+export async function applyDeferredAppContext(): Promise<void> {
+ const request = window.POSTHOG_APP_CONTEXT_REQUEST
+ if (!request) {
+ return
+ }
+ let deferred: DeferredAppContext
+ try {
+ deferred = await request
+ } catch {
+ window.location.replace(inlineAppContextUrl(window.location.href))
+ // The page is going away, so never let the boot continue without the user's data.
+ return new Promise(() => {})
+ }
+ window.POSTHOG_APP_CONTEXT = { ...window.POSTHOG_APP_CONTEXT, ...deferred.app_context } as AppContext
+ window.POSTHOG_USER_IDENTITY_WITH_FLAGS = {
+ ...window.POSTHOG_USER_IDENTITY_WITH_FLAGS,
+ featureFlags: deferred.feature_flags,
+ }
+ markBootPhase('app_context_loaded')
+}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 04515b29b9f2..805fe0789c11 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5337,6 +5337,8 @@ export interface TiledIconModuleProps {
export type EventOrPropType = EventDefinition & PropertyDefinition
export interface AppContext {
+ /** The page left out the user's data, and the app fetches it at boot. See lib/utils/deferredAppContext. */
+ deferred?: boolean
run_mode?: 'US' | 'EU' | 'DEV' | 'E2E' | 'LOCAL' | 'HOBBY'
current_user: UserType | null
current_project: ProjectType | null
diff --git a/posthog/frontend_views.py b/posthog/frontend_views.py
index ca92419169ed..78d637dfaf9d 100644
--- a/posthog/frontend_views.py
+++ b/posthog/frontend_views.py
@@ -1,16 +1,19 @@
import json
-from typing import Any
+from typing import Any, cast
from urllib.parse import urlparse
from django.conf import settings
-from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
+from django.http import HttpRequest, HttpResponse, HttpResponseRedirect, JsonResponse
+from django.utils.cache import patch_cache_control
from django.utils.http import url_has_allowed_host_and_scheme
from django.views.decorators.csrf import ensure_csrf_cookie
from posthog.cloud_utils import is_cloud
from posthog.dataclasses import frozen
from posthog.models.instance_setting import get_instance_setting
-from posthog.utils import render_template
+from posthog.models.user import User
+from posthog.templatetags.posthog_filters import TolerantJSONEncoder
+from posthog.utils import add_user_app_context, feature_flag_bootstrap, render_template
from posthog.views import login_required
APP_POSTHOG_HOST = "app.posthog.com"
@@ -171,3 +174,20 @@ def home_with_region_redirect(request: HttpRequest, *args: Any, **kwargs: Any) -
if region_redirect is not None:
return region_redirect
return _login_required_render_home(request, *args, **kwargs)
+
+
+def app_context(request: HttpRequest) -> JsonResponse:
+ """The signed-in user's part of the app context, for an app page rendered without it."""
+ if not request.user.is_authenticated:
+ return JsonResponse({"detail": "Authentication credentials were not provided."}, status=401)
+ posthog_app_context: dict[str, Any] = {}
+ add_user_app_context(request, posthog_app_context)
+ response = JsonResponse(
+ {
+ "app_context": posthog_app_context,
+ "feature_flags": feature_flag_bootstrap(cast(User, request.user), posthog_app_context["current_user"]),
+ },
+ encoder=TolerantJSONEncoder,
+ )
+ patch_cache_control(response, no_store=True)
+ return response
diff --git a/posthog/middleware.py b/posthog/middleware.py
index ec7fc297e7dd..b9b15620af04 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -1481,9 +1481,15 @@ class SocialAuthExceptionMiddleware:
# partner pays for, which this check also never judges. Settling the balance is how a member lifts
# a deactivation; no payment restores a pending deletion. `organizationLogic` holds the same table.
ALLOWED_WHILE_BLOCKED: dict[str, tuple[str, ...]] = {
- "/organization-pending-deletion": ("/organization-pending-deletion", "/signup/", "/agentic/authorize"),
+ "/organization-pending-deletion": (
+ "/organization-pending-deletion",
+ "/signup/",
+ "/agentic/authorize",
+ "/_app_context",
+ ),
"/organization-deactivated": (
"/organization-deactivated",
+ "/_app_context",
"/signup/",
"/agentic/authorize",
"/organization/billing",
diff --git a/posthog/templates/head.html b/posthog/templates/head.html
index 70777aa5e1c9..7bc64aa2d36d 100644
--- a/posthog/templates/head.html
+++ b/posthog/templates/head.html
@@ -1,6 +1,26 @@
<title>{{ page_title|default:"PostHog" }}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
+{% if posthog_app_context.deferred %}
+ {# Starts before anything else in the page, so the request runs while the JS downloads. #}
+ {# The page's project path makes the fetch load the page's project, even when another tab has switched the saved one. #}
+ <script nonce="{{ request.csp_nonce }}">
+ {# A stalled request rejects too, so the app reloads with the data inline instead of waiting forever. #}
+ window.POSTHOG_APP_CONTEXT_REQUEST = Promise.race([
+ fetch((window.location.pathname.match(/^\/project\/\d+/) || [''])[0] + '/_app_context', { credentials: 'same-origin' }).then(function (response) {
+ if (!response.ok) {
+ throw new Error('app context request failed: ' + response.status)
+ }
+ return response.json()
+ }),
+ new Promise(function (_resolve, reject) {
+ setTimeout(function () {
+ reject(new Error('app context request timed out'))
+ }, 10000)
+ }),
+ ])
+ </script>
+{% endif %}
{% for token in origin_trial_tokens %}
<meta http-equiv="origin-trial" content="{{ token }}">
{% endfor %}
diff --git a/posthog/test/test_get_context_for_template.py b/posthog/test/test_get_context_for_template.py
index 4488817b8ad8..3b2673f00a74 100644
--- a/posthog/test/test_get_context_for_template.py
+++ b/posthog/test/test_get_context_for_template.py
@@ -8,19 +8,23 @@ from unittest.mock import MagicMock
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.contrib.sessions.middleware import SessionMiddleware
-from django.http import HttpResponse
+from django.http import HttpRequest, HttpResponse
from django.template.loader import render_to_string
from django.test import RequestFactory, SimpleTestCase
from parameterized import parameterized
from posthog.api.tagged_item import set_tags_on_object
-from posthog.models import UserHomeSettings
+from posthog.frontend_views import app_context
+from posthog.models import Team, User, UserHomeSettings
from posthog.stable_chunks import StableChunks
+from posthog.templatetags.posthog_filters import TolerantJSONEncoder
from posthog.utils import (
+ DEFERRED_APP_CONTEXT_FLAG,
flags_for_app_evaluation_context,
get_context_for_template,
get_persisted_feature_flags_for_app_context,
+ should_defer_app_context,
)
from products.conversations.backend.services.identity import IDENTITY_CLAIM_MAX_AGE_SECONDS
@@ -125,6 +129,36 @@ class TestFlagsForAppEvaluationContext(SimpleTestCase):
assert flags_for_app_evaluation_context(None, definitions) is None
+class TestShouldDeferAppContext(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("test variant defers and reports", "", "test", True, True),
+ ("control variant renders inline and reports", "", "control", False, True),
+ ("outside the experiment renders inline silently", "", None, False, False),
+ ("param on beats control", "?deferred_app_context=1", "control", True, False),
+ ("param off beats test", "?deferred_app_context=0", "test", False, False),
+ ]
+ )
+ def test_only_the_test_variant_defers(self, _name, query, variant, expect_deferred, expect_exposure):
+ request = RequestFactory().get(f"/{query}")
+ user = User(distinct_id="user-1", email="[email protected]")
+
+ with (
+ mock.patch("posthog.utils.posthoganalytics.get_feature_flag", return_value=variant),
+ mock.patch("posthog.utils.posthoganalytics.capture") as capture,
+ ):
+ assert should_defer_app_context(request, user) is expect_deferred
+
+ if expect_exposure:
+ capture.assert_called_once_with(
+ "$feature_flag_called",
+ distinct_id="user-1",
+ properties={"$feature_flag": DEFERRED_APP_CONTEXT_FLAG, "$feature_flag_response": variant},
+ )
+ else:
+ capture.assert_not_called()
+
+
class TestGetContextForTemplate(APIBaseTest):
def test_get_context_for_template(self):
with (
@@ -359,3 +393,42 @@ class TestGetContextForTemplate(APIBaseTest):
}
else:
assert "stable_chunks_importmap" not in context
+
+ @mock.patch("posthog.utils.posthoganalytics.get_all_flags", return_value={"some-flag": True})
+ @mock.patch("posthog.utils.posthoganalytics.feature_flag_definitions", return_value=None)
+ def test_deferred_page_gets_the_user_data_from_app_context(self, _mock_definitions, _mock_get_all_flags):
+ def user_request(path: str) -> HttpRequest:
+ request = RequestFactory().get(path)
+ SessionMiddleware(lambda _request: HttpResponse()).process_request(request)
+ request.user = self.user
+ return request
+
+ inline = get_context_for_template("index.html", user_request("/?deferred_app_context=0"))
+ deferred = get_context_for_template("index.html", user_request("/?deferred_app_context=1"))
+ fetched = json.loads(app_context(user_request("/_app_context")).content)
+
+ assert deferred["posthog_app_context"]["deferred"] is True
+ assert deferred["posthog_app_context"]["current_user"] is None
+ assert "featureFlags" not in deferred["posthog_bootstrap"]
+ page_with_fetched = {**deferred["posthog_app_context"], **fetched["app_context"]}
+ page_with_fetched.pop("deferred")
+ assert page_with_fetched == json.loads(json.dumps(inline["posthog_app_context"], cls=TolerantJSONEncoder))
+ assert fetched["feature_flags"] == inline["posthog_bootstrap"]["featureFlags"]
+
+ def test_app_context_loads_the_project_in_its_path_not_the_saved_one(self):
+ page_team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)
+ assert self.user.team == self.team
+
+ response = self.client.get(f"/project/{page_team.pk}/_app_context")
+
+ assert response.status_code == 200
+ assert response.json()["app_context"]["current_team"]["id"] == page_team.pk
+
+ def test_app_context_refuses_an_anonymous_request(self):
+ request = RequestFactory().get("/_app_context")
+ request.user = AnonymousUser()
+
+ response = app_context(request)
+
+ assert response.status_code == 401
+ assert b"current_user" not in response.content
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index b68c828476a4..cc56fe152585 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -2213,8 +2213,10 @@ class TestActiveOrganizationMiddleware(APIBaseTest):
("deactivated_keeps_billing", "is_active", "/organization/billing", status.HTTP_200_OK),
("deactivated_keeps_stripe_return", "is_active", "/billing/authorization_status", status.HTTP_200_OK),
("deactivated_keeps_partner_consent", "is_active", "/agentic/authorize", status.HTTP_200_OK),
+ ("deactivated_keeps_app_context", "is_active", "/_app_context", status.HTTP_200_OK),
("pending_deletion_keeps_invites", "is_pending_deletion", "/signup/{invite_id}", status.HTTP_200_OK),
("pending_deletion_keeps_partner_consent", "is_pending_deletion", "/agentic/authorize", status.HTTP_200_OK),
+ ("pending_deletion_keeps_app_context", "is_pending_deletion", "/_app_context", status.HTTP_200_OK),
("pending_deletion_drops_billing", "is_pending_deletion", "/organization/billing", status.HTTP_302_FOUND),
(
"pending_deletion_drops_stripe_return",
diff --git a/posthog/urls.py b/posthog/urls.py
index b80c0eaebd54..4bf46e2bff5a 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -32,7 +32,7 @@ from posthog.api.sdk_health import sdk_health
from posthog.api.two_factor_qrcode import CacheAwareQRGeneratorView
from posthog.api.web_experiment import web_experiments
from posthog.ee_urls import ee_urlpatterns
-from posthog.frontend_views import home, home_with_region_redirect
+from posthog.frontend_views import app_context, home, home_with_region_redirect
from posthog.ingress.github.provider import build_github_provider
from posthog.ingress.views import build_webhook_view
from posthog.oauth2_urls import urlpatterns as oauth2_urls
@@ -135,6 +135,7 @@ urlpatterns = [
opt_slash_path("_health", health),
opt_slash_path("_stats", stats),
opt_slash_path("_preflight", preflight_check),
+ opt_slash_path(r"(?:project/\d+/)?_app_context", app_context),
# ee
*ee_urlpatterns,
path("scim/v2/<str:scim_slug>/Users", csrf_exempt(scim_views.SCIMUsersView.as_view()), name="scim_users"),
diff --git a/posthog/utils.py b/posthog/utils.py
index 927a91fd0028..acc066b64fed 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -677,19 +677,9 @@ def _build_template_context(
# Set the frontend app context
# nosemgrep: api-query-param-underscore -- shipped public API param, a rename breaks clients
if not request.GET.get("no-preloaded-app-context"):
- from posthog.api.project import ProjectSerializer
from posthog.api.shared import TeamPublicSerializer
- from posthog.api.team.team_serializer import TeamSerializer
- from posthog.api.user import UserSerializer
- from posthog.models.user_home_settings import UserHomeSettings
- from posthog.user_permissions import UserPermissions
from posthog.views import preflight_check
- from products.access_control.backend.facade.user_access_control import (
- ACCESS_CONTROL_RESOURCES,
- UserAccessControl,
- )
-
with tracer.start_as_current_span("template.preflight"):
preflight_payload = json.loads(preflight_check(request).getvalue())
@@ -714,73 +704,18 @@ def _build_template_context(
).data
elif request.user.pk:
user = cast("User", request.user)
-
- user_permissions = UserPermissions(user=user, team=user.team)
- user_access_control = UserAccessControl(user=user, team=user.team)
- team = user.team
- if team and not user_access_control.has_project_access:
- user.current_team = None
- user.team = None
- user.save(update_fields=["current_team"])
- user_permissions = UserPermissions(user=user, team=None)
- user_access_control = UserAccessControl(user=user, team=None)
- with tracer.start_as_current_span("template.rbac.effective"):
- effective_access: dict[str, Any] = {}
- for resource in ACCESS_CONTROL_RESOURCES:
- with tracer.start_as_current_span(f"template.rbac.effective.{resource}"):
- effective_access[resource] = user_access_control.effective_access_level_for_resource(resource)
- posthog_app_context["effective_resource_access_control"] = effective_access
- with tracer.start_as_current_span("template.rbac.levels"):
- resource_access: dict[str, Any] = {}
- for resource in ACCESS_CONTROL_RESOURCES:
- with tracer.start_as_current_span(f"template.rbac.levels.{resource}"):
- access = user_access_control.access_level_for_resource(resource)
- resource_access[resource] = access.access_level if access else None
- posthog_app_context["resource_access_control"] = resource_access
-
- with tracer.start_as_current_span("template.user_serializer"):
- user_serialized = UserSerializer(
- request.user,
- context={
- "request": request,
- "user_permissions": user_permissions,
- "user_access_control": user_access_control,
- },
- many=False,
- )
- posthog_app_context["current_user"] = user_serialized.data
- posthog_distinct_id = user_serialized.data.get("distinct_id")
-
- if user.team:
- with tracer.start_as_current_span("template.team_serializer"):
- team_serialized = TeamSerializer(
- user.team,
- context={
- "request": request,
- "user_permissions": user_permissions,
- "user_access_control": user_access_control,
- },
- many=False,
- )
- posthog_app_context["current_team"] = team_serialized.data
-
- with tracer.start_as_current_span("template.project_serializer"):
- project_serialized = ProjectSerializer(
- user.team.project,
- context={"request": request, "user_permissions": user_permissions},
- many=False,
+ if template_name == "index.html" and should_defer_app_context(request, user):
+ # The page fetches the user's data from `app_context` while its JS loads.
+ posthog_app_context["deferred"] = True
+ posthog_distinct_id = user.distinct_id
+ else:
+ add_user_app_context(request, posthog_app_context)
+ posthog_distinct_id = posthog_app_context["current_user"].get("distinct_id")
+ if posthog_distinct_id:
+ # don't forcefully set distinctID, as this breaks the link for anonymous users coming from `posthog.com`.
+ posthog_bootstrap["featureFlags"] = feature_flag_bootstrap(
+ user, posthog_app_context["current_user"]
)
- posthog_app_context["current_project"] = project_serialized.data
- posthog_app_context["frontend_apps"] = get_frontend_apps(user.team.pk)
- event_info = get_default_event_info(user.team)
- posthog_app_context["default_event_name"] = event_info["default_event_name"]
- posthog_app_context["has_pageview"] = event_info["has_pageview"]
- posthog_app_context["has_screen"] = event_info["has_screen"]
- posthog_app_context["has_person_email"] = get_has_person_email(user.team)
-
- with tracer.start_as_current_span("template.user_home_settings"):
- home_settings = UserHomeSettings.objects.filter(team=user.team, user=user).first()
- posthog_app_context["homepage"] = (home_settings.homepage or None) if home_settings else None
# Merge caller-provided keys into posthog_app_context (e.g. oauth_application from the authorize view).
# A key absent from this list never reaches `window.POSTHOG_APP_CONTEXT`, so the scene that reads it
@@ -796,23 +731,6 @@ def _build_template_context(
context["posthog_app_context"] = posthog_app_context
- if posthog_distinct_id:
- user = cast("User", request.user)
- identity = _flag_identity(posthog_app_context["current_user"], user.date_joined.isoformat())
-
- with tracer.start_as_current_span("template.feature_flag_bootstrap"):
- feature_flags = posthoganalytics.get_all_flags(
- posthog_distinct_id,
- only_evaluate_locally=True,
- person_properties=identity.person_properties,
- groups=identity.groups,
- group_properties=identity.group_properties,
- )
- # don't forcefully set distinctID, as this breaks the link for anonymous users coming from `posthog.com`.
- posthog_bootstrap["featureFlags"] = flags_for_app_evaluation_context(
- feature_flags, posthoganalytics.feature_flag_definitions()
- )
-
# 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.
@@ -891,6 +809,134 @@ def _build_template_context(
return context
+DEFERRED_APP_CONTEXT_FLAG = "deferred-app-context"
+DEFERRED_APP_CONTEXT_PARAM = "deferred_app_context"
+
+
+def should_defer_app_context(request: HttpRequest, user: "User") -> bool:
+ """
+ Whether the app page leaves out the user's data and fetches it from `app_context` instead.
+ The query param wins over the experiment, so a lab run can pick a side and a failed fetch can reload without it.
+ """
+ param = request.GET.get(DEFERRED_APP_CONTEXT_PARAM)
+ if param is not None:
+ return param == "1"
+ try:
+ variant = posthoganalytics.get_feature_flag(
+ DEFERRED_APP_CONTEXT_FLAG,
+ str(user.distinct_id),
+ person_properties={"email": user.email},
+ only_evaluate_locally=True,
+ # The SDK would report every signed-in user, so only the experiment's users are reported below.
+ send_feature_flag_events=False,
+ )
+ if isinstance(variant, str):
+ posthoganalytics.capture(
+ "$feature_flag_called",
+ distinct_id=str(user.distinct_id),
+ properties={"$feature_flag": DEFERRED_APP_CONTEXT_FLAG, "$feature_flag_response": variant},
+ )
+ return variant == "test"
+ except Exception as e:
+ capture_exception(e)
+ return False
+
+
+def feature_flag_bootstrap(user: "User", current_user: dict[str, Any]) -> Optional[dict[str, Any]]:
+ distinct_id = current_user.get("distinct_id")
+ if not distinct_id:
+ return None
+ identity = _flag_identity(current_user, user.date_joined.isoformat())
+ with tracer.start_as_current_span("template.feature_flag_bootstrap"):
+ feature_flags = posthoganalytics.get_all_flags(
+ distinct_id,
+ only_evaluate_locally=True,
+ person_properties=identity.person_properties,
+ groups=identity.groups,
+ group_properties=identity.group_properties,
+ )
+ return flags_for_app_evaluation_context(feature_flags, posthoganalytics.feature_flag_definitions())
+
+
+def add_user_app_context(request: HttpRequest, posthog_app_context: dict[str, Any]) -> None:
+ """Adds the signed-in user's user, team, project and access data to the app context."""
+ from posthog.api.project import ProjectSerializer
+ from posthog.api.team.team_serializer import TeamSerializer
+ from posthog.api.user import UserSerializer
+ from posthog.models.user_home_settings import UserHomeSettings
+ from posthog.user_permissions import UserPermissions
+
+ from products.access_control.backend.facade.user_access_control import ACCESS_CONTROL_RESOURCES, UserAccessControl
+
+ user = cast("User", request.user)
+
+ user_permissions = UserPermissions(user=user, team=user.team)
+ user_access_control = UserAccessControl(user=user, team=user.team)
+ team = user.team
+ if team and not user_access_control.has_project_access:
+ user.current_team = None
+ user.team = None
+ user.save(update_fields=["current_team"])
+ user_permissions = UserPermissions(user=user, team=None)
+ user_access_control = UserAccessControl(user=user, team=None)
+ with tracer.start_as_current_span("template.rbac.effective"):
+ effective_access: dict[str, Any] = {}
+ for resource in ACCESS_CONTROL_RESOURCES:
+ with tracer.start_as_current_span(f"template.rbac.effective.{resource}"):
+ effective_access[resource] = user_access_control.effective_access_level_for_resource(resource)
+ posthog_app_context["effective_resource_access_control"] = effective_access
+ with tracer.start_as_current_span("template.rbac.levels"):
+ resource_access: dict[str, Any] = {}
+ for resource in ACCESS_CONTROL_RESOURCES:
+ with tracer.start_as_current_span(f"template.rbac.levels.{resource}"):
+ access = user_access_control.access_level_for_resource(resource)
+ resource_access[resource] = access.access_level if access else None
+ posthog_app_context["resource_access_control"] = resource_access
+
+ with tracer.start_as_current_span("template.user_serializer"):
+ user_serialized = UserSerializer(
+ request.user,
+ context={
+ "request": request,
+ "user_permissions": user_permissions,
+ "user_access_control": user_access_control,
+ },
+ many=False,
+ )
+ posthog_app_context["current_user"] = user_serialized.data
+
+ if user.team:
+ with tracer.start_as_current_span("template.team_serializer"):
+ team_serialized = TeamSerializer(
+ user.team,
+ context={
+ "request": request,
+ "user_permissions": user_permissions,
+ "user_access_control": user_access_control,
+ },
+ many=False,
+ )
+ posthog_app_context["current_team"] = team_serialized.data
+
+ with tracer.start_as_current_span("template.project_serializer"):
+ project_serialized = ProjectSerializer(
+ user.team.project,
+ context={"request": request, "user_permissions": user_permissions},
+ many=False,
+ )
+ posthog_app_context["current_project"] = project_serialized.data
+ posthog_app_context["frontend_apps"] = get_frontend_apps(user.team.pk)
+ event_info = get_default_event_info(user.team)
+ posthog_app_context["default_event_name"] = event_info["default_event_name"]
+ posthog_app_context["has_pageview"] = event_info["has_pageview"]
+ posthog_app_context["has_screen"] = event_info["has_screen"]
+ posthog_app_context["has_person_email"] = get_has_person_email(user.team)
+
+ with tracer.start_as_current_span("template.user_home_settings"):
+ home_settings = UserHomeSettings.objects.filter(team=user.team, user=user).first()
+ posthog_app_context["homepage"] = (home_settings.homepage or None) if home_settings else None
+
+
def render_template(
template_name: str,
request: HttpRequest,