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.

perf(frontend): land on the post-login page in one document load (#95273)

Paul D'Ambra6e212fdfc08b
diff --git a/frontend/src/scenes/authentication/login-2fa/login2FALogic.ts b/frontend/src/scenes/authentication/login-2fa/login2FALogic.ts
index 0711da55049f..49c52a99aba1 100644
--- a/frontend/src/scenes/authentication/login-2fa/login2FALogic.ts
+++ b/frontend/src/scenes/authentication/login-2fa/login2FALogic.ts
@@ -6,7 +6,7 @@ import { loaders } from 'kea-loaders'
import api, { ApiError } from 'lib/api'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { handleLoginRedirect } from 'scenes/authentication/login/loginLogic'
+import { redirectAfterLogin } from 'scenes/authentication/login/loginLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { getPasskeyErrorMessage, isWebAuthnCancellation } from 'scenes/settings/user/passkeys/utils'
@@ -287,9 +287,7 @@ export const login2FALogic = kea<login2FALogicType>([
})),
listeners(({ values }) => ({
submitTwofactortokenSuccess: () => {
- handleLoginRedirect()
- // Reload the page after login to ensure POSTHOG_APP_CONTEXT is set correctly.
- window.location.reload()
+ redirectAfterLogin()
},
beginPasskey2FASuccess: () => {
// The loader returns null on user cancellation to avoid surfacing
@@ -299,9 +297,7 @@ export const login2FALogic = kea<login2FALogicType>([
if (values.passkey2FAWasCancelled) {
return
}
- handleLoginRedirect()
- // Reload the page after login to ensure POSTHOG_APP_CONTEXT is set correctly.
- window.location.reload()
+ redirectAfterLogin()
},
})),
afterMount(({ actions }) => {
diff --git a/frontend/src/scenes/authentication/login/loginLogic.test.ts b/frontend/src/scenes/authentication/login/loginLogic.test.ts
index 3e6b8fb296b7..8e7ced85b137 100644
--- a/frontend/src/scenes/authentication/login/loginLogic.test.ts
+++ b/frontend/src/scenes/authentication/login/loginLogic.test.ts
@@ -4,7 +4,7 @@ import { expectLogic, testUtilsPlugin } from 'kea-test-utils'
import posthog from 'posthog-js'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
-import { handleLoginRedirect, loginLogic } from 'scenes/authentication/login/loginLogic'
+import { handleLoginRedirect, loginLogic, redirectAfterLogin } from 'scenes/authentication/login/loginLogic'
import { passkeyLogic } from 'scenes/authentication/shared/passkeyLogic'
import { initKea } from '~/initKea'
@@ -545,4 +545,89 @@ describe('loginLogic', () => {
expect(hrefSpy).toHaveBeenCalledWith('/project/phc_ABC123/pipeline/destinations')
})
})
+
+ describe('redirectAfterLogin', () => {
+ const originalLocation = window.location
+ let replaceSpy: jest.Mock
+ let assignSpy: jest.Mock
+ let reloadSpy: jest.Mock
+
+ beforeEach(() => {
+ initKeaTests()
+ replaceSpy = jest.fn()
+ assignSpy = jest.fn()
+ reloadSpy = jest.fn()
+ Object.defineProperty(window, 'location', {
+ value: {
+ origin: 'http://localhost',
+ pathname: '/login',
+ search: '',
+ hash: '',
+ replace: replaceSpy,
+ assign: assignSpy,
+ reload: reloadSpy,
+ },
+ configurable: true,
+ })
+ })
+
+ afterEach(() => {
+ Object.defineProperty(window, 'location', { value: originalLocation, configurable: true })
+ })
+
+ it('lands on the app root in a single document load', () => {
+ router.actions.push('/login')
+ redirectAfterLogin()
+ expect(replaceSpy).toHaveBeenCalledTimes(1)
+ expect(replaceSpy).toHaveBeenCalledWith('/')
+ // A second navigation would cancel every chunk the first boot had started fetching
+ expect(reloadSpy).not.toHaveBeenCalled()
+ })
+
+ it('takes the place of the login entry, so Back does not return to it', () => {
+ router.actions.push('/login')
+ redirectAfterLogin()
+ expect(assignSpy).not.toHaveBeenCalled()
+ })
+
+ it('lands on the next path, keeping its query and hash', () => {
+ router.actions.push(`/login?next=${encodeURIComponent('/project/5/insights?foo=bar')}#tab=raw`)
+ redirectAfterLogin()
+ expect(replaceSpy).toHaveBeenCalledTimes(1)
+ expect(replaceSpy).toHaveBeenCalledWith('/project/5/insights?foo=bar#tab=raw')
+ })
+
+ it('ignores a next path pointing at another origin', () => {
+ router.actions.push('/login?next=//google.com')
+ redirectAfterLogin()
+ expect(replaceSpy).toHaveBeenCalledWith('/')
+ })
+
+ it('prefers an explicit destination over the next path', () => {
+ router.actions.push(`/login?next=${encodeURIComponent('/project/5/insights')}`)
+ redirectAfterLogin('/project/5/replay/home')
+ expect(replaceSpy).toHaveBeenCalledTimes(1)
+ expect(replaceSpy).toHaveBeenCalledWith('/project/5/replay/home')
+ })
+
+ it('rejects an explicit cross-origin destination', () => {
+ router.actions.push('/login')
+ redirectAfterLogin('https://evil.example/steal')
+ expect(replaceSpy).toHaveBeenCalledWith('/')
+ })
+
+ it('rejects a protocol-relative cross-origin destination', () => {
+ router.actions.push('/login')
+ redirectAfterLogin('//evil.example/steal')
+ expect(replaceSpy).toHaveBeenCalledWith('/')
+ })
+
+ it('accepts an absolute destination on our own origin, as its path', () => {
+ // The guard must not over-reject: a same-origin absolute URL is a legitimate
+ // destination, and it arrives as a path.
+ router.actions.push('/login')
+ redirectAfterLogin('http://localhost/project/5/insights?foo=bar#tab=raw')
+ expect(replaceSpy).toHaveBeenCalledWith('/project/5/insights?foo=bar#tab=raw')
+ })
+ })
})
diff --git a/frontend/src/scenes/authentication/login/loginLogic.ts b/frontend/src/scenes/authentication/login/loginLogic.ts
index 4432bc2db0c4..03e5ecf12fe2 100644
--- a/frontend/src/scenes/authentication/login/loginLogic.ts
+++ b/frontend/src/scenes/authentication/login/loginLogic.ts
@@ -98,8 +98,9 @@ function pointsToDifferentProject(path: string): boolean {
return !!identifier && identifier !== String(getCurrentTeamIdOrNone())
}
-export function handleLoginRedirect(): void {
- let nextURL = '/'
+/** 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) || '/'
@@ -107,11 +108,19 @@ export function handleLoginRedirect(): void {
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
- nextURL = url.pathname + url.search + encodeParams(router.values.hashParams, '#')
+ return url.pathname + url.search + encodeParams(router.values.hashParams, '#')
}
} catch {
// do nothing
}
+ return '/'
+}
+
+/** Leave the login screen for a session that is already authenticated, e.g. someone opening
+ * `/login` in a second tab. The app context in this document is already the logged-in one, so the
+ * redirect can stay client-side. Straight after authenticating, use `redirectAfterLogin` instead. */
+export function handleLoginRedirect(): void {
+ const nextURL = loginRedirectTarget()
// 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))) {
@@ -131,6 +140,21 @@ export function handleLoginRedirect(): void {
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())
+}
+
export interface LoginForm {
email: string
password: string
@@ -635,15 +659,11 @@ export const loginLogic = kea<loginLogicType>([
submitLoginSuccess: () => {
// A logged-in session reads the address from the user, so drop the stored one
clearPendingVerificationEmail()
- handleLoginRedirect()
- // Reload the page after login to ensure POSTHOG_APP_CONTEXT is set correctly.
- window.location.reload()
+ redirectAfterLogin()
},
submitCodeVerificationSuccess: () => {
clearPendingVerificationEmail()
- handleLoginRedirect()
- // Reload the page after login to ensure POSTHOG_APP_CONTEXT is set correctly.
- window.location.reload()
+ redirectAfterLogin()
},
exitCodeVerification: () => {
actions.resetCodeVerification()
diff --git a/frontend/src/scenes/authentication/shared/devLoginLogic.ts b/frontend/src/scenes/authentication/shared/devLoginLogic.ts
index 4e448f4d2542..4925bd3fc00a 100644
--- a/frontend/src/scenes/authentication/shared/devLoginLogic.ts
+++ b/frontend/src/scenes/authentication/shared/devLoginLogic.ts
@@ -150,7 +150,7 @@ export const devLoginLogic = kea<devLoginLogicType>([
listeners(({ actions }) => ({
devLogin: async ({ email }) => {
// Dynamic import to avoid a circular dependency: loginLogic statically imports this logic.
- const { loginLogic, handleLoginRedirect } = await import('scenes/authentication/login/loginLogic')
+ const { loginLogic, redirectAfterLogin } = await import('scenes/authentication/login/loginLogic')
loginLogic.actions.clearGeneralError()
try {
await api.create<any>('api/login/dev', { email })
@@ -159,8 +159,7 @@ export const devLoginLogic = kea<devLoginLogicType>([
loginLogic.actions.setGeneralError(code || 'dev_login_failed', detail || 'Dev login failed')
return
}
- handleLoginRedirect()
- window.location.reload()
+ redirectAfterLogin()
},
createFreshAccount: async () => {
try {
diff --git a/frontend/src/scenes/authentication/shared/passkeyLogic.ts b/frontend/src/scenes/authentication/shared/passkeyLogic.ts
index bea1fdd5295f..fa22ad2f858f 100644
--- a/frontend/src/scenes/authentication/shared/passkeyLogic.ts
+++ b/frontend/src/scenes/authentication/shared/passkeyLogic.ts
@@ -11,7 +11,7 @@ import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
import { isWebKitBrowser } from 'lib/utils/dom'
-import { handleLoginRedirect, loginLogic } from 'scenes/authentication/login/loginLogic'
+import { loginLogic, redirectAfterLogin } from 'scenes/authentication/login/loginLogic'
import { getPasskeyErrorMessage, isWebAuthnCancellation } from 'scenes/settings/user/passkeys/utils'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
@@ -257,8 +257,7 @@ export const passkeyLogic = kea<passkeyLogicType>([
useBrowserAutofill: true,
})
await api.create('api/webauthn/login/complete/', assertion)
- handleLoginRedirect()
- window.location.reload()
+ redirectAfterLogin()
} catch (e: unknown) {
// The autofill passkey prompt is routinely dismissed — the user types a password
// instead, or navigates away. Swallow those; surface anything genuinely wrong.
@@ -284,14 +283,9 @@ export const passkeyLogic = kea<passkeyLogicType>([
return
}
- // For regular login, redirect and reload
- if (values.redirectLink) {
- router.actions.push(values.redirectLink)
- } else {
- handleLoginRedirect()
- }
-
- window.location.reload()
+ // For regular login, load the destination as a fresh document so its app context is the
+ // logged-in one. `redirectLink` is guarded against other origins by `redirectAfterLogin`.
+ redirectAfterLogin(values.redirectLink)
},
startPasskeyAuthenticationFailure: () => {
// Reset state on real authentication failures so the user can fall