: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
import { encodeParams, router } from 'kea-router'
import posthog from 'posthog-js'
import { getCurrentTeamIdOrNone, isUserLoggedIn } from 'lib/utils/getAppContext'
import { getRelativeNextPath } from 'lib/utils/url'
// Routes that should be handled by Django, not the React router
const BACKEND_ONLY_ROUTES = [
'/login/vercel/continue',
'/oauth/authorize',
'/toolbar_oauth/authorize',
'/toolbar_oauth/check',
]
const PROJECT_PATH_PREFIX = '/project/'
// True when the path targets a project other than the one we're currently in. A client-side
// history replace can't switch the active project, so `AutoProjectMiddleware` never runs and any
// team-scoped scene resolves against the wrong project and 404s. The project segment is either a
// numeric team id or a token (a `phc_` project key, or a legacy api_token from the middleware's
// switching allowlist), and only the server can resolve a token to a team, so anything that isn't
// literally the current team id takes the full load.
function pointsToDifferentProject(path: string): boolean {
if (!path.startsWith(PROJECT_PATH_PREFIX)) {
return false
}
const identifier = path.slice(PROJECT_PATH_PREFIX.length).split('/')[0]
return !!identifier && identifier !== String(getCurrentTeamIdOrNone())
}
/** Where the user should land after logging in: `?next=` when the server-side `login_required()`
* decorator put one there, otherwise the app root. Always same-origin. */
function loginRedirectTarget(): string {
try {
const nextPath = getRelativeNextPath(router.values.searchParams['next'], location) || '/'
const url = new URL(location.origin + nextPath)
if (url.protocol === 'http:' || url.protocol === 'https:') {
// Note that the hash MUST be handled client-side because /login?next= is generated by the server-side
// `login_required()` decorator, and hash params never make it to the server
return url.pathname + url.search + encodeParams(router.values.hashParams, '#')
}
} catch {
// do nothing
}
return '/'
}
const SIGNED_OUT_PAGE_FULL_LOAD_KEY = 'ph_signed_out_page_full_load'
const SIGNED_OUT_PAGE_FULL_LOAD_WINDOW_MS = 30_000
type SignedOutPageFullLoadClaim = 'claimed' | 'repeated' | 'storage_unavailable'
/** A server that keeps rendering the session signed out would send the new document straight back to
* /login, so a target gets one full load per window and the next attempt stays client-side. */
function claimFullLoadFromSignedOutPage(nextURL: string): SignedOutPageFullLoadClaim {
try {
const previous = JSON.parse(window.sessionStorage.getItem(SIGNED_OUT_PAGE_FULL_LOAD_KEY) ?? 'null')
if (previous?.url === nextURL && Date.now() - previous.at < SIGNED_OUT_PAGE_FULL_LOAD_WINDOW_MS) {
return 'repeated'
}
window.sessionStorage.setItem(SIGNED_OUT_PAGE_FULL_LOAD_KEY, JSON.stringify({ url: nextURL, at: Date.now() }))
return 'claimed'
} catch {
// Without storage there is no loop guard, and an unguarded full load can reload forever.
return 'storage_unavailable'
}
}
/** Leave the login screen for a session that is already authenticated, e.g. someone opening
* `/login` in a second tab. When the app context in this document is already the logged-in one, the
* redirect can stay client-side. Straight after authenticating, use `redirectAfterLogin` instead. */
export function handleLoginRedirect(): void {
const nextURL = loginRedirectTarget()
// The server rendered this page for a signed-out visitor, so its app context has no user and its
// stable chunk import map holds only the signed-out scenes. The app must arrive as a new document.
if (!isUserLoggedIn()) {
const claim = claimFullLoadFromSignedOutPage(nextURL)
if (claim === 'claimed') {
// Replace rather than assign so the stale signed-out document doesn't stay in history —
// otherwise Back would return to /login, or redirect into the app again.
window.location.replace(nextURL)
return
}
if (claim === 'repeated') {
posthog.capture('signed-out page redirect repeated')
} else {
posthog.capture('signed-out page redirect skipped', { reason: claim })
}
}
// Check if this is a backend-only route that shouldn't go through the React router
if (BACKEND_ONLY_ROUTES.some((route) => nextURL.startsWith(route))) {
window.location.href = nextURL
return
}
// A cross-project deep link needs a full page load so `AutoProjectMiddleware` can switch the
// active project before the scene mounts. A client-side replace would strip the project id and
// resolve the scene against the project we were last in, 404ing a resource that really exists.
if (pointsToDifferentProject(nextURL)) {
window.location.href = nextURL
return
}
// A safe way to redirect to a user input URL. Calls history.replaceState() ensuring the URLs origin does not change
router.actions.replace(nextURL)
}
/** Land on the post-login page in a single document load.
*
* `POSTHOG_APP_CONTEXT` is injected into the HTML, so a document served to a logged-out visitor
* still describes a logged-out one. The destination must arrive as a new document, and it takes
* the place of the login entry in history.
*
* An explicit destination must resolve to a same-origin path. That also rules out a bare fragment
* or query string. The guard falls back to `loginRedirectTarget()`, which checks `?next=` the
* same way. */
export function redirectAfterLogin(destination?: string): void {
const guardedDestination = destination ? getRelativeNextPath(destination, location) : null
// Replace, so Back does not return to the login screen
window.location.replace(guardedDestination || loginRedirectTarget())
}