: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
feat(frontend): prefetch the scene behind the root and fixed redirects (#127885)
Paul D'Ambra632928663569
diff --git a/frontend/src/scenes/prefetchScene.test.ts b/frontend/src/scenes/prefetchScene.test.tsindex a3e6342ae84a..5d2192eeee81 100644--- a/frontend/src/scenes/prefetchScene.test.ts+++ b/frontend/src/scenes/prefetchScene.test.ts@@ -1,8 +1,13 @@+import posthog from 'posthog-js'++import { FEATURE_FLAGS } from 'lib/constants'import { appScenes } from 'scenes/appScenes'import { prefetchScene, sceneForPathname } from 'scenes/prefetchScene'-import { Scene } from 'scenes/sceneTypes'+import { Scene, SceneTab } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'+import { AppContext } from '~/types'+describe('prefetchScene', () => {afterEach(() => {jest.restoreAllMocks()@@ -14,14 +19,38 @@ describe('prefetchScene', () => {['a page with params', `/project/1${urls.replaySingle('abc')}`, Scene.ReplaySingle],['a trailing slash', `/project/1${urls.savedInsights()}/`, Scene.SavedInsights],['a page outside a project', urls.savedInsights(), Scene.SavedInsights],- ['a redirect that also matches a route', '/project/1/replay/recent', null],- ['the root', '/', null],+ ['a redirect to a fixed path', '/project/1/events', Scene.ExploreEvents],+ ['a redirect that builds its path and also matches a route', '/project/1/replay/recent', null],+ ['the root', '/', Scene.ProjectHomepage],+ ['the project root', '/project/1', Scene.ProjectHomepage],+ ['the homepage', '/project/1/home', Scene.ProjectHomepage],['an unknown page', '/project/1/no-such-page/at-all', null],['a path that does not decode', '/project/1/person/50%off', null],])('finds the scene for %s', (_case, pathname, expected) => {expect(sceneForPathname(pathname)).toEqual(expected)})+ it.each(+ ['/', '/project/1', '/project/1/home'].flatMap((pathname) => [+ [pathname, false, Scene.SavedInsights] as const,+ [pathname, true, Scene.ProjectHomepage] as const,+ ])+ )('finds the scene for %s with a configured homepage (today rail nav: %s)', (pathname, todayRailNav, expected) => {+ jest.spyOn(posthog, 'isFeatureEnabled').mockImplementation(+ (key) => key === FEATURE_FLAGS.TODAY_RAIL_NAV && todayRailNav+ )+ const appContext = window.POSTHOG_APP_CONTEXT+ window.POSTHOG_APP_CONTEXT = {+ ...appContext,+ homepage: { pathname: `/project/1${urls.savedInsights()}`, search: '', hash: '' } as SceneTab,+ } as AppContext+ try {+ expect(sceneForPathname(pathname)).toEqual(expected)+ } finally {+ window.POSTHOG_APP_CONTEXT = appContext+ }+ })+it.each([['throws',diff --git a/frontend/src/scenes/prefetchScene.ts b/frontend/src/scenes/prefetchScene.tsindex 59ec74004a67..f0ef092a8636 100644--- a/frontend/src/scenes/prefetchScene.ts+++ b/frontend/src/scenes/prefetchScene.ts@@ -1,17 +1,48 @@import posthog from 'posthog-js'import UrlPattern from 'url-pattern'+import { FEATURE_FLAGS } from 'lib/constants'import { markBootPhase } from 'lib/utils/bootTiming'import { pathFromWindowToRoutes, urlPatternOptions } from 'lib/utils/kea-router'import { appScenes } from 'scenes/appScenes'+import { getBootstrappedHomepage, homepageTargetPathname } from 'scenes/sceneLogic'import { redirects, routes } from 'scenes/scenes'+import { urls } from 'scenes/urls'function matchesRoute(pattern: string, path: string): boolean {const staticPrefix = pattern.split(/[:*(]/)[0]return path.startsWith(staticPrefix) && new UrlPattern(pattern, urlPatternOptions).match(path) !== null}-/** The scene that sceneLogic opens for `pathname`, or null when a redirect handles it or no route matches. */+function routePath(target: string): string {+ return pathFromWindowToRoutes(target.split(/[?#]/)[0])+}++/** Follows at most one redirect or homepage hop, so a redirect loop cannot recurse. */+function sceneForRoutePath(path: string, followRedirects: boolean): string | null {+ // sceneLogic sends `/` to the homepage, so the root resolves the same way as `/home`.+ const homePath = urls.projectHomepage()+ const matchPath = path === '/' ? homePath : path+ const redirect = Object.entries(redirects).find(([pattern]) => matchesRoute(pattern, matchPath))+ if (redirect) {+ const [, target] = redirect+ // A function target builds its path from the request's params and query, which the boot does not resolve.+ return followRedirects && typeof target === 'string' ? sceneForRoutePath(routePath(target), false) : null+ }+ // sceneLogic ignores a saved homepage when the rail navigation is on, and opens the project homepage instead.+ const followsSavedHomepage =+ followRedirects &&+ matchPath === homePath &&+ !posthog.isFeatureEnabled(FEATURE_FLAGS.TODAY_RAIL_NAV, { send_event: false })+ const homepage = followsSavedHomepage ? getBootstrappedHomepage() : null+ if (homepage) {+ return sceneForRoutePath(routePath(homepageTargetPathname(homepage)), false)+ }+ const route = Object.entries(routes).find(([pattern]) => matchesRoute(pattern, matchPath))+ return route ? route[1][0] : null+}++/** The scene that sceneLogic opens for `pathname`, or null when it cannot be known before the router runs. */export function sceneForPathname(pathname: string): string | null {let path: stringtry {@@ -19,11 +50,7 @@ export function sceneForPathname(pathname: string): string | null {} catch {return null}- if (path === '/' || Object.keys(redirects).some((pattern) => matchesRoute(pattern, path))) {- return null- }- const route = Object.entries(routes).find(([pattern]) => matchesRoute(pattern, path))- return route ? route[1][0] : null+ return sceneForRoutePath(path, true)}/**diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsxindex eca4d23c6602..e453b953ff68 100644--- a/frontend/src/scenes/sceneLogic.tsx+++ b/frontend/src/scenes/sceneLogic.tsx@@ -126,7 +126,7 @@ function leaveBlockedOrganizationPath(): boolean {// `/` and `/home` both resolve the configured homepage through this, so anything asking whether a// location is the homepage has to derive it the same way.-const homepageTargetPathname = (homepage: SceneTab): string => {+export const homepageTargetPathname = (homepage: SceneTab): string => {const targetPathname = addProjectIdIfMissing(homepage.pathname || urls.projectHomepage())return removeProjectIdIfPresent(targetPathname) === '/'? addProjectIdIfMissing(urls.projectHomepage())@@ -135,7 +135,7 @@ const homepageTargetPathname = (homepage: SceneTab): string => {// 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 => {+export const getBootstrappedHomepage = (): SceneTab | null => {const homepage = getAppContext()?.homepageif (!homepage) {return null