: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
fix(navigation): honor configured homepage when visiting /home directly (#60847)
Paul D'Ambra58cfe21426ef
diff --git a/frontend/src/scenes/sceneLogic.test.tsx b/frontend/src/scenes/sceneLogic.test.tsxindex 08ff5ac247dd..265f6dd3ae66 100644--- a/frontend/src/scenes/sceneLogic.test.tsx+++ b/frontend/src/scenes/sceneLogic.test.tsx@@ -4,11 +4,13 @@ import { expectLogic, partial, truth } from 'kea-test-utils'import api from 'lib/api'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { removeProjectIdIfPresent } from 'lib/utils/router-utils'import { Scene } from 'scenes/sceneTypes'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { initKeaTests } from '~/test/init'+import type { AppContext } from '~/types'import { mergePinnedTabs, sceneLogic } from './sceneLogic'import type { testLogicType, tabAwareTestLogicType } from './sceneLogic.testType'@@ -221,6 +223,89 @@ describe('sceneLogic', () => {expect(tab3Instances[0].pinned).toBe(false)expect(pinnedTabs.map((tab) => tab.id)).not.toContain('tab-3')})+ describe('/home honors the configured homepage', () => {+ const dashboardHomepage = {+ id: 'homepage-dashboard-42',+ pathname: urls.dashboard(42),+ search: '',+ hash: '',+ title: 'Default dashboard',+ iconType: 'dashboard' as const,+ active: false,+ pinned: true,+ sceneId: Scene.Dashboard,+ sceneKey: 'dashboard-42',+ sceneParams: { params: {}, searchParams: {}, hashParams: {} },+ }++ it('redirects /home to the configured dashboard homepage', async () => {+ logic.actions.setHomepage(dashboardHomepage)+ router.actions.push(urls.projectHomepage())+ await expectLogic(logic).delay(1)+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual(urls.dashboard(42))+ })++ it('stays on the launchpad at /home when no homepage is configured', async () => {+ logic.actions.setHomepage(null)+ router.actions.push(urls.projectHomepage())+ await expectLogic(logic).delay(1)+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual(urls.projectHomepage())+ })++ it('bootstraps the homepage from APP_CONTEXT so a direct /home visit redirects on first paint', async () => {+ logic.unmount()+ const priorAppContext = window.POSTHOG_APP_CONTEXT+ let bootstrappedHomepagePathname = ''+ let redirectedPathname = ''+ try {+ initKeaTests()+ window.POSTHOG_APP_CONTEXT = {+ ...window.POSTHOG_APP_CONTEXT,+ homepage: dashboardHomepage,+ } as unknown as AppContext+ ;(api.get as jest.Mock).mockResolvedValue({ tabs: [], homepage: null })+ ;(api.update as jest.Mock).mockResolvedValue({ tabs: [], homepage: null })+ await expectLogic(teamLogic).toDispatchActions(['loadCurrentTeamSuccess'])+ featureFlagLogic.mount()+ router.actions.push(urls.eventDefinitions())+ const bootstrappedLogic = sceneLogic.build({ scenes: testScenes })+ // Simulate a fresh mount the same way the suite's beforeEach does.+ bootstrappedLogic.cache.tabsLoaded = false+ bootstrappedLogic.mount()+ // homepage is populated synchronously from APP_CONTEXT — no setHomepage / API round-trip needed.+ bootstrappedHomepagePathname = removeProjectIdIfPresent(+ bootstrappedLogic.values.homepage?.pathname ?? ''+ )+ router.actions.push(urls.projectHomepage())+ await expectLogic(bootstrappedLogic).delay(1)+ redirectedPathname = removeProjectIdIfPresent(router.values.location.pathname)+ } finally {+ window.POSTHOG_APP_CONTEXT = priorAppContext+ }+ expect(bootstrappedHomepagePathname).toEqual(urls.dashboard(42))+ expect(redirectedPathname).toEqual(urls.dashboard(42))+ })++ it('forwards allow-listed query params onto the homepage redirect and drops the rest', async () => {+ logic.actions.setHomepage(dashboardHomepage)+ router.actions.push(urls.projectHomepage(), { modal: 'feature', other: 'dropped' })+ await expectLogic(logic).delay(1)+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual(urls.dashboard(42))+ expect(router.values.searchParams).toEqual({ modal: 'feature' })+ })++ it('does not loop when the launchpad is the homepage and a forwarded param is present', async () => {+ logic.actions.setHomepage({+ ...dashboardHomepage,+ id: 'homepage-launchpad',+ pathname: urls.projectHomepage(),+ })+ router.actions.push(urls.projectHomepage(), { modal: 'feature' })+ await expectLogic(logic).delay(1)+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual(urls.projectHomepage())+ expect(router.values.searchParams).toEqual({ modal: 'feature' })+ })+ })describe('mergePinnedTabs', () => {const tabBase = { search: '', hash: '', title: '', iconType: 'blank' as const }diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsxindex d1f99abb45a7..4f2c20663df2 100644--- a/frontend/src/scenes/sceneLogic.tsx+++ b/frontend/src/scenes/sceneLogic.tsx@@ -97,6 +97,13 @@ const sanitizeTabForPersistence = (tab: SceneTab): SceneTab => {return tabToPersistableSnapshot(tab, { pinned: true, active: false })}+// Bootstrapped by Django into APP_CONTEXT so the configured homepage is known on first paint,+// before any async fetch — otherwise urlToAction runs with a null homepage and /home can't redirect.+const getBootstrappedHomepage = (): SceneTab | null => {+ const homepage = getAppContext()?.homepage+ return homepage ? sanitizeTabForPersistence(homepage) : null+}+const persistTabs = (_tabs: SceneTab[], _homepage: SceneTab | null): void => {// PostHog tabs were removed — no longer persist tab state to storage.}@@ -591,14 +598,16 @@ export const sceneLogic = kea<sceneLogicType>([},],}),- reducers({+ // Function form so the bootstrapped default is read at build time (per kea context),+ // not once at module import — production sets APP_CONTEXT before the bundle loads either way.+ reducers(() => ({homepage: [- null as SceneTab | null,+ getBootstrappedHomepage(),{setHomepage: (_, { tab }) => (tab ? sanitizeTabForPersistence(tab) : null),},],- }),+ })),selectors({activeTab: [(s) => [s.tabs],@@ -855,8 +864,7 @@ export const sceneLogic = kea<sceneLogicType>([}},setHomepage: ({ tab }) => {- if (isSharedView() || cache.skipNextHomepageSync) {- cache.skipNextHomepageSync = false+ if (isSharedView()) {return}api.update('api/user_home_settings/@me/', {@@ -1291,21 +1299,6 @@ export const sceneLogic = kea<sceneLogicType>([])cache.initialNavigationTabCreated = true}-- if (!isSharedView() && !cache.homepageLoaded) {- cache.homepageLoaded = true- ;(async () => {- try {- const response = await api.get<{ homepage?: SceneTab | null }>('api/user_home_settings/@me/')- if (response?.homepage) {- cache.skipNextHomepageSync = true- actions.setHomepage(response.homepage)- }- } catch (error) {- console.error('Failed to load homepage', error)- }- })()- }}),urlToAction(({ actions, values, cache }) => {@@ -1360,37 +1353,49 @@ export const sceneLogic = kea<sceneLogicType>([)}}- mapping['/'] = (_params, searchParams) => {+ // The Home button (via `/`) and a direct visit to /home should both land on the user's+ // configured homepage (set in the Configure home modal). Redirect there unless we're+ // already at it, which also guards against loops when the homepage is the launchpad itself.+ const redirectToConfiguredHomepage = (searchParams: Params): boolean => {const homepage = values.homepage-- if (homepage) {- let targetPathname = homepage.pathname- ? addProjectIdIfMissing(homepage.pathname)- : urls.projectHomepage()- if (targetPathname === '/') {- targetPathname = urls.projectHomepage()- }- const targetSearch = homepage.search || ''- const targetHash = homepage.hash || ''- const loc = router.values.currentLocation- // Already at homepage: skip replace or replaceState loops (e.g. homepage === project root).- const alreadyAtHomepage =- addProjectIdIfMissing(loc.pathname) === addProjectIdIfMissing(targetPathname) &&- (loc.search || '') === targetSearch &&- (loc.hash || '') === targetHash- if (!alreadyAtHomepage) {- router.actions.replace(targetPathname, targetSearch, targetHash)- return- }+ if (!homepage) {+ return false+ }+ let targetPathname = addProjectIdIfMissing(homepage.pathname || urls.projectHomepage())+ if (removeProjectIdIfPresent(targetPathname) === '/') {+ targetPathname = addProjectIdIfMissing(urls.projectHomepage())+ }+ // Forward allow-listed params (e.g. modal) onto the homepage the same way the launchpad+ // redirect does, and compare against that final target so a forwarded param can't loop.+ const target = withForwardedSearchParams(+ targetPathname + (homepage.search || '') + (homepage.hash || ''),+ searchParams,+ forwardedRedirectQueryParams+ )+ const loc = router.values.currentLocation+ if (addProjectIdIfMissing(loc.pathname) + (loc.search || '') + (loc.hash || '') === target) {+ return false}+ router.actions.replace(target)+ return true+ }+ mapping['/'] = (_params, searchParams) => {+ if (redirectToConfiguredHomepage(searchParams)) {+ return+ }router.actions.replace(withForwardedSearchParams(urls.projectHomepage(), searchParams, forwardedRedirectQueryParams))}+ const projectHomepagePath = urls.projectHomepage()for (const [path, [scene, sceneKey]] of Object.entries(routes)) {mapping[path] = (params, searchParams, hashParams, { method }) => {+ // A direct visit to /home honors the configured homepage just like the Home button.+ if (path === projectHomepagePath && redirectToConfiguredHomepage(searchParams)) {+ return+ }const tabId = ensureNavigationTabId()actions.openScene(scene,diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex ee260ece02f5..0b16fb5dfe07 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -36,7 +36,7 @@ import type { ProjectSecretAPIKeyAllowedScope } from 'lib/scopes'import { BehavioralFilterKey, BehavioralFilterType } from 'scenes/cohorts/CohortFilters/types'import { BreakdownColorConfig } from 'scenes/dashboard/DashboardInsightColorsModal'import { AggregationAxisFormat } from 'scenes/insights/aggregationAxisFormat'-import { Params, Scene, SceneConfig } from 'scenes/sceneTypes'+import { Params, Scene, SceneConfig, SceneTab } from 'scenes/sceneTypes'import { SessionRecordingPlayerMode } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'import { SurveyRatingScaleValue, WEB_SAFE_FONTS } from 'scenes/surveys/constants'@@ -4824,6 +4824,8 @@ export interface AppContext {suggested_users_with_access?: UserBasicType[]livestream_host?: stringoauth_application?: OAuthApplicationPublicMetadata+ /** The user's configured homepage for the current team, bootstrapped so navigation can honor it on first paint. */+ homepage?: SceneTab | null}export type StoredMetricMathOperations = 'max' | 'min' | 'sum'diff --git a/posthog/test/test_get_context_for_template.py b/posthog/test/test_get_context_for_template.pyindex f6eb47be9e16..ca69c410c7bd 100644--- a/posthog/test/test_get_context_for_template.py+++ b/posthog/test/test_get_context_for_template.py@@ -1,7 +1,16 @@+import json+from posthog.test.base import APIBaseTestfrom unittest import mockfrom unittest.mock import MagicMock+from django.contrib.sessions.middleware import SessionMiddleware+from django.http import HttpResponse+from django.test import RequestFactory++from parameterized import parameterized++from posthog.models import UserHomeSettingsfrom posthog.utils import get_context_for_template@@ -39,3 +48,23 @@ class TestGetContextForTemplate(APIBaseTest):)assert actual["stripe_public_key"] == "pk_test_12345"++ @parameterized.expand(+ [+ ("configured", {"pathname": "/dashboard/42", "pinned": True, "title": "Default dashboard"}),+ ("not_configured", None),+ ("empty_is_cleared", {}),+ ]+ )+ def test_bootstraps_configured_homepage_into_app_context(self, _name, stored_homepage):+ if stored_homepage is not None:+ UserHomeSettings.objects.create(user=self.user, team=self.team, homepage=stored_homepage)++ request = RequestFactory().get("/")+ SessionMiddleware(lambda _request: HttpResponse()).process_request(request)+ request.user = self.user++ actual = get_context_for_template("layout", request)++ app_context = json.loads(actual["posthog_app_context"])+ assert app_context["homepage"] == (stored_homepage or None)diff --git a/posthog/utils.py b/posthog/utils.pyindex b92c6f1970a8..30aa53e57f21 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -489,6 +489,7 @@ def _build_template_context(from posthog.api.team import TeamSerializerfrom posthog.api.user import UserSerializerfrom posthog.models.file_system.user_product_list import UserProductList+ from posthog.models.user_home_settings import UserHomeSettingsfrom posthog.rbac.user_access_control import ACCESS_CONTROL_RESOURCES, UserAccessControlfrom posthog.user_permissions import UserPermissionsfrom posthog.views import preflight_check@@ -593,6 +594,10 @@ def _build_template_context(capture_exception()posthog_app_context["promoted_product_intent"] = None+ 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)if "oauth_application" in context:posthog_app_context["oauth_application"] = context.pop("oauth_application")