[$250] Account - System back button on 2FA success RHP navigates to Account > Security
If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.
Version Number: 9.5.28-4 Reproducible in staging?: Yes Reproducible in production?: Yes If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://github.com/Expensify/App/pull/102482 Email or phone of affected tester (no customers): [email protected] Issue reported by: Applause Internal Team Bug source: Exploratory - Significant User Experience Deterioration Device used: Web, android App Component: User Settings
Action Performed:
Preconditions: Account A owns a workspace that requires 2FA (e.g. Xero connected). Account B already finished onboarding and has 2FA disabled. As Account A, invite Account B to the workspace as an Admin.
- Go to staging.new.expensify.com
- Log in as Account B
- Click "Enable two-factor authentication"
- Complete setup by copying codes and entering the 6-digit code
- Press the system back button on the success page
Expected Result:
System back button on 2FA success RHP should lead to Home
Actual Result:
System back button on 2FA success RHP leads to Account > Security instead of Home. The same happens on web: clicking outside the RHP and browser back button
Workaround:
Unknown
Platforms:
- [x] Android: App
- [ ] Android: mWeb Chrome
- [ ] iOS: App
- [ ] iOS: mWeb Safari
- [ ] iOS: mWeb Chrome
- [x] Windows: Chrome
- [ ] MacOS: Chrome Safari
Screenshots/Videos
https://github.com/user-attachments/assets/959f85f2-90a7-4416-8a2f-fb69fb2da1c4
Applause Internal Information Exported by: Chandana Kiran Bug ID: 7303063
Issue Owner
Current Issue Owner: @neerajbachaniUpwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022119624565783727951
- Upwork Job ID: 2119624565783727951
- Last Price Increase: 2026-11-09
While Applause doesn't embed attachments for this bug, here are the links for quick view: https://platform.applause.com/services/links/v1/external/0323890c7b8f9b71e5c692c5b53012715a0b3cdd0f914c900e519f014e9071d9
Proposal
What is the root cause of that problem?
Send users Home after required 2FA setup instead of Settings > Security only redirects two exits on the success page: Got it and the header back arrow. Both call sendForcedSetupUserHome() in DynamicSuccessPage.tsx:90-127.
Three other exits skip that code. Each one pops the whole RHP. That reveals the screen underneath, which is Settings > Security (settings/security?forceSetup=true):
- Android back button:
goBackreaches only the header arrow. Nothing on the 2FA pages listens for the hardware back button, so react-navigation pops the RHP. - Clicking outside the RHP:
handleOverlayPresscallsnavigation.goBack()on the root stack (RightModalNavigator.tsx:250-268). The 2FAbeforeRemovelistener there only clears 2FA data (lines 327-334). - Browser back: the previous history entry is
settings/security?forceSetup=true, so popstate goes back to it.
What changes do you think we should make in order to solve the problem?
In DynamicSuccessPage, intercept every way of removing the screen during a forced setup, not just the button handlers:
- Add a
usePreventRemoveguard that is on whenisForcedSetupFlow || shouldReturnToOnboardingAfter2FA. - When the guard fires, don't replay the original action (that pops to Security). Instead, call the same branch
goBack()uses:sendForcedSetupUserHome()orcompleteForcedOnboarding2FAHandoff(). - Turn the guard off (state flag) before those helpers dismiss the modal, so their own dismissal isn't blocked.
- Add tests to
DynamicSuccessPageTestfor the overlay press and the back action. Check that voluntary setup from Settings > Security (noforceSetup) is not guarded.
All three exits fire beforeRemove on the success screen, so one guard covers them. It also fixes the same leak in the incomplete-onboarding handoff, which today can drop the user on Security instead of resuming onboarding.
VacationDelegateMissingWorkspacesPage already uses usePreventRemove this way (index.tsx:95).
What alternative solutions did you explore? (Optional)
useAndroidBackButtonHandlercallinggoBack(): fixes Android only. The overlay click and browser back stay broken.- Replace Settings > Security with Home under the RHP after verification: fixes the overlay and Android back. It doesn't fix browser back, because the history entry for
settings/security?forceSetup=truestays.
Investigation details
- I traced this from the code at
82c9505, which includes the PR above. I didn't reproduce it, because that needs a workspace that requires 2FA, such as one with Xero connected. - The setup, verify and success steps replace each other (
DynamicVerifyPage.tsx:63). So the success page is the only screen in the 2FA stack, and any back action closes the whole RHP. - Still to confirm: on web, browser back could take react-navigation's
resetRootpath instead ofgoBack.beforeRemovedoesn't fire on that path. If it does, browser back needs a separate fix. Check this on web before you finalize the PR. - Home can render behind the RHP at this point because 2FA is already on.
sendForcedSetupUserHomealready reveals Home from the same screen.
Related issues:
- [$175] 2FA - After setup 2FA new workspace user is stay in Account option: the original issue. The PR above fixed its Got it path.
Next Steps for Contributor+ team:
To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/105693) to create a draft PR.
To refine: @MelvinBot <your feedback>
To reject: Explain why you are rejecting Melvin's proposal.
Triggered auto assignment to Contributor-plus team member for initial proposal review - @daledah (External)
Unable to auto-create job on Upwork. The BZ team member should create it manually for this issue.
Root cause: the 2FA success screen sits in the RHP stack on top of Account > Security, so a system back press (Android) or browser back / click-outside (web) simply pops one level to Security instead of exiting the flow — but the expected landing after a completed 2FA setup is Home.
Fix: make the success screen replace the Security entry in the navigation history (or dismiss the whole RHP stack on back), so pressing back from the success screen lands on Home rather than stepping back into Security.
I will verify: on Android system back, web browser back, and clicking outside the RHP, the success screen exits to Home; and Settings > Account > Security remains reachable normally afterwards.
Proposal
What is the root cause of that problem?
In PR #102482, sendForcedSetupUserHome() was hooked up exclusively to the explicit on-screen button handlers in DynamicSuccessPage.tsx:90-127: the header back arrow (goBack) and the primary "Got it" button (onButtonPress).
DynamicSuccessPage does not intercept stack removal events. Consequently, when a user exits via:
- Android hardware / system back button,
- Clicking the modal backdrop overlay outside the RHP on web (
handleOverlayPressinRightModalNavigator.tsx:250), - Browser back button (
popstate), or - Keyboard Escape key,
React Navigation directly pops the RightModalNavigator off the root navigation stack. Because the forced 2FA flow was opened on top of settings/security?forceSetup=true (RequireTwoFactorAuthenticationOverlay.tsx:116-119), popping the RHP directly reveals Account > Security underneath rather than navigating to Home.
Furthermore, in DynamicSuccessPage.tsx:
const isForcedSetupFlow = isSecuritySettingsFlow && route.params?.forceSetup === 'true';
isForcedSetupFlow is coupled to isSecuritySettingsFlow (dynamically derived from getStateFromPath(dynamicBackPath)). Once Navigation.revealRouteBeforeDismissingModal(ROUTES.HOME) replaces the fullscreen route underneath the RHP with HOME, isSecuritySettingsFlow evaluates to false during the dismissal animation. The forced setup status must be derived authoritatively from route.params?.forceSetup === 'true'.
(Note: MelvinBot's attempted PR #106178 failed because it used usePreventRemove with a deferred useEffect state toggle, which caused race conditions and blank-page lockups on web when popstate had already altered the browser history stack, and lacked action-type discrimination for DISMISS_MODAL).
What changes do you think we should make in order to solve the problem?
1. Derive isForcedSetup directly from screen route params
In src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx:
- Decouple the forced-setup check from the underlying route so it remains stable throughout the entire lifecycle of the screen:
const isForcedSetup = route.params?.forceSetup === 'true';
2. Intercept Screen Removal via a beforeRemove Navigation Listener
In DynamicSuccessPage.tsx, register a beforeRemove listener on navigation active during forced setup (isForcedSetup || shouldReturnToOnboardingAfter2FA):
- Intercept any unhandled removal actions (Android back, overlay click, browser back, Escape key):
- Prevent default removal (
e.preventDefault()). - Use an
isExitingRefto prevent re-entrant duplicate triggers from rapid clicks. - Call the existing
goBack(), which cleanly executessendForcedSetupUserHome()(orcompleteForcedOnboarding2FAHandoff()).
- Prevent default removal (
- Allow the final dismiss action through:
- When
sendForcedSetupUserHome()executes, it callsNavigation.revealRouteBeforeDismissingModal(ROUTES.HOME), which dispatchesCONST.NAVIGATION.ACTION_TYPE.DISMISS_MODAL. - When
e.data.action.type === CONST.NAVIGATION.ACTION_TYPE.DISMISS_MODAL, allow the action to proceed unimpeded so the RHP slides out smoothly over Home.
- When
const isExitingRef = useRef(false);
useEffect(() => {
if (!isForcedSetup && !shouldReturnToOnboardingAfter2FA) {
return;
}
const unsubscribe = navigation.addListener('beforeRemove', (e) => {
// Allow the intentional DISMISS_MODAL dispatched by revealRouteBeforeDismissingModal through
if (e.data.action.type === CONST.NAVIGATION.ACTION_TYPE.DISMISS_MODAL) {
return;
}
e.preventDefault();
if (isExitingRef.current) {
return;
}
isExitingRef.current = true;
goBack();
});
return unsubscribe;
}, [isForcedSetup, shouldReturnToOnboardingAfter2FA, navigation, goBack]);
3. Preserve Voluntary 2FA Setup
When a user sets up 2FA voluntarily from Settings > Security (without forceSetup=true):
isForcedSetupisfalse.- The
beforeRemovelistener is not attached, and voluntary setups preserve their existing behavior (navigating toROUTES.SETTINGS_2FA_ENABLEDviaonButtonPress).
4. Before and After Results
Before (on main):
- Completing forced 2FA setup lands on 2FA Success page.
- Pressing Android system back, clicking outside the modal overlay, or pressing browser back pops the RHP directly, dropping the user back to Account > Security (
/settings/security):- Bug reproduction recording: https://github.com/user-attachments/assets/959f85f2-90a7-4416-8a2f-fb69fb2da1c4
- Screenshot of bug outcome (lands on Security):
After (with our fix):
- Completing forced 2FA setup lands on 2FA Success page.
- Pressing Android system back, clicking outside the modal overlay, or pressing browser back is intercepted by the
beforeRemovelistener, executingsendForcedSetupUserHome(), smoothly dismissing the RHP, and landing the user on Home (/home) with zero blank pages:- Screenshot of expected outcome (lands on Home):
- Screenshot of expected outcome (lands on Home):
| Verification Matrix | Expected Result | Actual Result with Fix |
|---|---|---|
| Android Hardware Back Button | Navigate to Home (/home) |
✅ Lands on Home |
| Modal Backdrop Overlay Click (Web) | Navigate to Home (/home) |
✅ Lands on Home |
| Browser Back Button (Web) | Navigate to Home (/home) |
✅ Lands on Home |
| Keyboard Escape Key | Navigate to Home (/home) |
✅ Lands on Home |
| Voluntary 2FA Setup (from Settings) | Keep on Enabled Page (SETTINGS_2FA_ENABLED) |
✅ Stays on Enabled Page |
| Incomplete Onboarding Forced 2FA | Resume Onboarding Handoff | ✅ Resumes Onboarding |
5. Automated Tests
In tests/unit/pages/settings/Security/TwoFactorAuth/DynamicSuccessPageTest.tsx:
- Add test asserting that dismissing the RHP via Android system back or overlay click when
forceSetup === 'true'navigates toROUTES.HOME. - Add test asserting that dismissing the RHP when
shouldReturnToOnboardingAfter2FA === trueexecutes the onboarding handoff (resumeOnboardingAfterRequired2FASetup). - Add test verifying that voluntary 2FA setup (
forceSetup=undefined) does not intercept dismissal and navigates toSETTINGS_2FA_ENABLED.
What alternative solutions did you explore? (Optional)
useAndroidBackButtonHandler: Only intercepts the Android hardware back button; leaves modal backdrop clicks, keyboard Escape, and web browser back still revealingSettings > Security.usePreventRemovewith state toggling inuseEffect(PR #106178): Causes race conditions on web when browserpopstatehas already altered history, leading to blank page freezes and broken second-back navigation.- Modifying
handleOverlayPressinRightModalNavigator: Pollutes global modal navigation with two-factor-specific route checks and does not solve Android hardware back or browser back.
Contributor details
Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374
Proposal
Please re-state the problem that we are trying to solve in this issue.
In a forced 2FA setup flow (e.g. an invited admin to a workspace that requires 2FA), completing the setup opens the 2FA Success page. Pressing the Android hardware/system back button, clicking outside the Right Hand Pane (RHP) overlay on web, or pressing the browser back button navigates the user to Account > Security (settings/security?forceSetup=true) instead of navigating them to Home.
What is the root cause of that problem?
In src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx (lines 90-127):
sendForcedSetupUserHome() is only hooked up to the header back button (onBackButtonPress={goBack}) and the primary "Got it" button (onButtonPress).
When a user:
- Presses the Android hardware back button,
- Clicks outside the RHP modal overlay (triggering
handleOverlayPressinRightModalNavigator.tsx), or - Uses the browser back button,
the dismissal bypasses goBack() and executes directly on the root/modal stack navigator. Because the 2FA flow was initiated from settings/security?forceSetup=true, popping the RHP reveals Settings > Security underneath rather than returning the user to Home.
What changes do you think we should make in order to solve the problem?
In src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx:
- Import
usePreventRemovefrom@react-navigation/nativeanduseReffromreact. - Add a
usePreventRemoveguard active when(isForcedSetupFlow || shouldReturnToOnboardingAfter2FA). - Use a
isDismissingRefflag to prevent blocking our custom dismissal:
--- a/src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx
+++ b/src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx
@@ -29,8 +29,8 @@ import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES, {DYNAMIC_ROUTES} from '@src/ROUTES';
import SCREENS from '@src/SCREENS';
import {hasCompletedGuidedSetupFlowSelector} from '@src/selectors/Onboarding';
import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue';
-import {findFocusedRoute} from '@react-navigation/native';
+import {findFocusedRoute, usePreventRemove} from '@react-navigation/native';
import {authTokenTypeSelector} from '@selectors/Session';
-import React from 'react';
+import React, {useRef} from 'react';
import SuccessPageBase from './SuccessPageBase';
@@ -53,4 +53,12 @@ function DynamicSuccessPage({route}: DynamicSuccessPageProps) {
const isForcedSetupFlow = isSecuritySettingsFlow && route.params?.forceSetup === 'true';
+ const isDismissingRef = useRef(false);
+ usePreventRemove(
+ (isForcedSetupFlow || shouldReturnToOnboardingAfter2FA) && !isDismissingRef.current,
+ () => {
+ isDismissingRef.current = true;
+ goBack();
+ },
+ );
When beforeRemove is intercepted, goBack() is triggered, properly executing sendForcedSetupUserHome() or completeForcedOnboarding2FAHandoff() to navigate the user to Home.
What alternative solutions did you explore? (Optional)
- Using
useAndroidBackButtonHandler: This only handles Android hardware back and leaves click-outside-overlay and browser back still falling back toSettings > Security.usePreventRemoveintercepts all screen removal actions uniformly.
What automated tests can you add to prevent this from re-occurring?
In tests/unit/DynamicSuccessPageTest.tsx:
- Verify that when
isForcedSetupFlow === true, triggering abeforeRemoveevent on the navigation container executessendForcedSetupUserHome(). - Verify that voluntary 2FA setup from Settings > Security (
isForcedSetupFlow === false) is not intercepted.
Contributor Track Record & Details
- Proven Open-Source Contributor: Successfully merged pull requests in major enterprise repositories including Microsoft .NET runtime (PR reference: dotnet/runtime#136828).
- Ready for Fast Turnaround: Full environment configured, ready to push clean PR with passing Jest tests immediately upon assignment.
Proposal
Please re-state the problem that we are trying to solve in this issue.
In a forced 2FA setup flow (e.g., an invited admin to a workspace that requires 2FA), completing 2FA displays the success page. Pressing the Android hardware/system back button, clicking the web modal backdrop overlay outside the RHP, or using the browser back button lands the user on Account > Security (settings/security?forceSetup=true) instead of navigating them to Home.
What is the root cause of that problem?
In src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx:
sendForcedSetupUserHome()(or the custom forced-setup dismissal) is only wired up to the explicit UI buttons: the header back arrow (onBackButtonPress={goBack}) and the primary button (onButtonPress).- When the user:
- Presses the Android hardware back button,
- Clicks outside the RHP modal overlay (triggering
handleOverlayPressinRightModalNavigator.tsx), or - Presses the browser back button,
the navigation dismissal bypasses
goBack()and executes directly on the root/modal navigator stack.
- Because the 2FA flow was launched on top of
settings/security?forceSetup=true, popping the RHP revealsSettings > Securityunderneath rather than returning the user to Home.
What changes do you think we should make in order to solve the problem?
In src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx:
- Import
usePreventRemovefrom@react-navigation/nativeanduseReffromreact. - Add a
usePreventRemovehook active when(isForcedSetupFlow || shouldReturnToOnboardingAfter2FA):
const isDismissingRef = useRef(false);
usePreventRemove(
(isForcedSetupFlow || shouldReturnToOnboardingAfter2FA) && !isDismissingRef.current,
() => {
isDismissingRef.current = true;
goBack();
},
);
- When
beforeRemoveis intercepted,goBack()is triggered.goBack()routes throughsendForcedSetupUserHome()(orcompleteForcedOnboarding2FAHandoff()), which properly navigates the user to Home (or resumes onboarding) before dismissing the modal. TheisDismissingRefguard ensures that the subsequent programmatic dismissal is not blocked.
What alternative solutions did you explore? (Optional)
useAndroidBackButtonHandler: Explored, but rejected because it only handles Android hardware back events and leaves web backdrop clicks and browser back actions unhandled.usePreventRemovecleanly intercepts all removal vectors uniformly across all platforms.
What automated tests can you add to prevent this from re-occurring?
In tests/unit/DynamicSuccessPageTest.tsx:
- Add a test verifying that when
isForcedSetupFlowistrue, dispatching abeforeRemovenavigation event executessendForcedSetupUserHome(). - Add a test verifying that when voluntary 2FA is set up from Settings > Security (
isForcedSetupFlow === false),beforeRemoveis not intercepted.
Contributor details
Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0105126232377c4c5c
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
@MelvinBot implement this
🤖 Web test steps verification results: ⚠️ partial
The supplied web session remained blank with zero UI nodes, so none of the requested 2FA behaviors could be verified.

| Step | Status |
|---|---|
Required-workspace admin login/setupBlocked by the blank session; admin status and required workspace could not be confirmed.![]() ![]() |
⚠️ |
Recovery codes and six-digit verification reach successNot exercised: setup was inaccessible. |
⚠️ |
Browser Back from success leads HomeNot exercised: success was inaccessible. |
⚠️ |
Outside-RHP click from success leads HomeNot exercised: success was inaccessible. |
⚠️ |
Voluntary Security setup and navigation remain unchangedNot exercised: no Security controls were available. |
⚠️ |
Implemented in draft PR Route forced two-factor success dismissals to Home, assigned to daledah. Forced dismissals now use the existing Home/onboarding handoff; voluntary setup is unchanged.
Automated checks: 11 focused tests, lint, typecheck, spelling, source-file React Compiler check, and Storybook smoke test passed. Full Jest timed out after 10 minutes without reported failures. Formatting checks were unavailable or policy-blocked; compiler changed-file detection failed on an empty base reference.
Browser verification remains required before marking the PR ready for review.
view run · no recording available
Proposal
Please re-state the problem that we are trying to solve in this issue.
After completing required two-factor authentication (2FA) setup (forceSetup=true) and landing on the 2FA Success RHP screen, pressing the Android hardware/system back button, clicking outside the RHP overlay, or pressing the browser back button pops the RHP and lands the user on Account > Security (settings/security?forceSetup=true) instead of navigating them to Home like the "Got it" button and header back arrow do.
What is the root cause of that problem?
In src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx (lines 90–127), PR #102482 wired only the "Got it" primary button and the HeaderWithBackButton back arrow to call sendForcedSetupUserHome() when isForcedSetup is true. Three other exit paths bypass sendForcedSetupUserHome() and pop the RightModalNavigator back to the underlying settings/security?forceSetup=true screen:
- The Android hardware back button is not intercepted on
DynamicSuccessPage.tsx(useAndroidBackButtonHandleris not called, so React Navigation executes its defaultGO_BACKaction). - Clicking outside the RHP calls
handleOverlayPressinsrc/libs/Navigation/AppNavigator/Navigators/RightModalNavigator.tsx(lines 250–268), which dispatchesnavigation.goBack()on the root stack. - The 2FA
beforeRemovelistener insrc/libs/Navigation/AppNavigator/Navigators/RightModalNavigator.tsx(lines 327–334) only callsTwoFactorAuthActions.clearTwoFactorAuthData()and does not redirect forced-setup users toROUTES.HOMEwhen the 2FA flow is dismissed after 2FA has been enabled.
What changes do you think we should make in order to solve the problem?
- In
src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx:- Register
useAndroidBackButtonHandlerso pressing the Android system back button calls the samegoBack()handler (which runssendForcedSetupUserHome()whenisForcedSetupis true and returnstrueto prevent the default pop).
- Register
- In
src/libs/Navigation/AppNavigator/Navigators/RightModalNavigator.tsxinside the 2FAbeforeRemovelistener (lines 327–334) (or inDynamicSuccessPage.tsxviauseBeforeRemove):- Check if the 2FA modal is being removed while on the 2FA success step (or when
account?.requiresTwoFactorAuthis true andforceSetupwas active) without having already calledsendForcedSetupUserHome(). - When dismissed via overlay press or browser back under forced setup, call
sendForcedSetupUserHome()(Navigation.navigate(ROUTES.HOME, {forceReplace: true})) afterTwoFactorAuthActions.clearTwoFactorAuthData().
- Check if the 2FA modal is being removed while on the 2FA success step (or when
- Add a unit/navigation test in
tests/unit/NavigationTest.tsverifying that dismissing the 2FA success RHP underforceSetup=truevia back/dismiss routes toROUTES.HOME.
What alternative solutions did you explore? (Optional)
We considered replacing the underlying settings/security?forceSetup=true route with ROUTES.HOME using usePreMountDestination as soon as the user reaches DynamicSuccessPage, which is also clean, but handling useAndroidBackButtonHandler and beforeRemove directly ensures both hardware back and browser back behave identically to "Got it".
📣 @jeffrey-graham! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:
- Make sure you've read and understood the contributing guidelines.
- Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
- Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
📣 @ronanchnlps-bit! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:
- Make sure you've read and understood the contributing guidelines.
- Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
- Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
Proposal
Please re-state the problem that we are trying to solve in this issue.
On the 2FA (Two-Factor Authentication) success screen, pressing the system/browser back button returns the user to Account > Security or the intermediate 2FA setup form instead of returning to the settings root.
What is the root cause of that problem?
In TwoFactorAuthPage.tsx:
When two-factor authentication is successfully verified, navigation to the success screen uses Navigation.navigate(ROUTES.SETTINGS_2FA_SUCCESS) which appends the success view on top of the navigation stack. Consequently, pressing the hardware/browser back button traverses back through the already-completed 2FA setup screens.
What changes do you think we should make in order to solve the problem?
- In
TwoFactorAuthPage.tsx:- Replace the navigation action with
Navigation.replace(ROUTES.SETTINGS_2FA_SUCCESS)or dismiss the setup modal stack upon completion. - On the success screen, configure back navigation to route cleanly to
ROUTES.SETTINGS_SECURITYwith a cleared sub-flow history.
- Replace the navigation action with
What alternative solutions did you explore? (Optional)
Overriding hardware back button listener only, but replacing route entries in navigation history is cross-platform and fixes web browser back buttons as well.
Melvin’s proposal has some navigation and blank page bugs, so I’ve opened this issue to contributors to get more eyes on it
Proposal
Please re-state the problem that we are trying to solve in this issue.
Complete a mandatory 2FA setup flow. Pressing Android back, browser back, or clicking the backdrop overlay on the success screen lands on Account > Security instead of Home.
What is the root cause of that problem?
In PR #102482, the author connected sendForcedSetupUserHome() only to explicit on-screen buttons: "Got it" and the header back button. Alternative dismissals like Android system back, modal backdrop clicks, and browser back pop RightModalNavigator directly off the root stack. Forced 2FA setup mounts over settings/security?forceSetup=true. Popping the modal directly reveals Settings > Security underneath rather than redirecting to Home. The success page lacks an exit interceptor to catch parent modal dismissals during forced setup flows.
What changes do you think we should make in order to solve the problem?
In src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx:
- Add
shouldExitForcedSetupstate,hasExitedForcedSetupref, and attachusePreventRemove:
const [shouldExitForcedSetup, setShouldExitForcedSetup] = useState(false);
const hasExitedForcedSetup = useRef(false);
usePreventRemove((isForcedSetupFlow || shouldReturnToOnboardingAfter2FA) && !shouldExitForcedSetup, () => {
setShouldExitForcedSetup(true);
});
- Add a
useEffectto execute the dismissal handoff after the removal guard disarms:
useEffect(() => {
if (!shouldExitForcedSetup || hasExitedForcedSetup.current) {
return;
}
hasExitedForcedSetup.current = true;
if (shouldReturnToOnboardingAfter2FA) {
completeForcedOnboarding2FAHandoff();
return;
}
sendForcedSetupUserHome();
}, [shouldExitForcedSetup, shouldReturnToOnboardingAfter2FA, completeForcedOnboarding2FAHandoff, sendForcedSetupUserHome]);
- Update
goBackandonButtonPressto route forced setup flows throughsetShouldExitForcedSetup(true).
Why the component must disarm the guard in a committed render:
usePreventRemove coordinates through React Navigation's PreventRemoveContext. The context only updates when the component re-renders with shouldExitForcedSetup = true. Calling sendForcedSetupUserHome() synchronously without disabling the guard causes Navigation.revealRouteBeforeDismissingModal()'s subsequent DISMISS_MODAL action to hit the guard again. This pattern disables the guard in a committed render before modal dismissal runs. The ref hasExitedForcedSetup prevents duplicate triggers.
- Add unit test coverage in
tests/unit/pages/settings/Security/TwoFactorAuth/DynamicSuccessPageTest.tsxcovering backdrop dismissal, hardware back, and voluntary setup.
Test branch: fix/105693-system-back-2fa-success-rhp-home
Results demonstrating the fix (After):
- Web (backdrop click): https://github.com/samithreddychinni/App/releases/download/v105693-proof/web-after-1.mp4
- Mobile (system back): https://github.com/samithreddychinni/App/releases/download/v105693-proof/mobile-after.mp4
What alternative solutions did you explore? (Optional)
- Using a synchronous ref with
usePreventRemovewithout state:usePreventRemoveconsumes a render-time prop. Mutating a ref does not trigger a re-render, so the listener continues blocking the subsequent programmatic modal dismissal. - Using
useAndroidBackButtonHandler: only intercepts Android hardware back. It fails to handle backdrop overlay clicks and browser back actions on web.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01cfe51584d8033bdc
🚨 Edited by proposal-police: This proposal was edited at 2026-11-09 12:53:23 UTC.
Proposal
What is the root cause of that problem?
The require-2FA overlay opens setup on top of settings/security?forceSetup=true, so Security stays under the RHP for the whole flow:
https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/src/pages/RequireTwoFactorAuthenticationOverlay.tsx#L118
#102482 sends that user Home only from the two callbacks of the success page, "Got it" and the header back arrow:
https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx#L82-L98
Android back, browser back and the click outside never call them. They remove the whole RHP from the root stack (the overlay press is a plain root goBack()), and the only beforeRemove on the 2FA RHP just clears 2FA data. So the RHP closes onto Security:
https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/src/libs/Navigation/AppNavigator/Navigators/RightModalNavigator.tsx#L250-L262
Why just blocking the removal and calling the helper (what #106178 did) gives the blank page / navigation bugs: the helper's Home swap runs in a requestAnimationFrame, not in the same call.
https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/src/libs/Navigation/Navigation.ts#L1231-L1238
On browser back the browser has already moved when beforeRemove fires. If the listener prevents removal and nothing is dispatched in that same call, react-navigation's useLinking rolls history back with an async history.go() (rollbackHistoryIfPrevented). The late swap and dismiss then land on top of that rollback.
What changes do you think we should make in order to solve the problem?
Keep the existing helpers as the only exit, but let them do the Home swap right away when the call comes from a removal.
Navigation.revealRouteBeforeDismissingModal: addshouldRevealImmediately. When set, run theREPLACE_FULLSCREEN_UNDER_RHPpart synchronously instead of in the first rAF. The dismiss stays on the next frame, so the animation is the same as "Got it".DynamicSuccessPage: anisLeavingForcedFlowRefset at the top ofsendForcedSetupUserHome/completeForcedOnboarding2FAHandoff(lets their own dismiss through and stops a double back from starting a second reveal), plus ouruseBeforeRemove:
useBeforeRemove((event) => {
if (isLeavingForcedFlowRef.current || !(shouldReturnToOnboardingAfter2FA || isForcedSetupFlow)) {
return;
}
event.preventDefault();
shouldReturnToOnboardingAfter2FA ? completeForcedOnboarding2FAHandoff(true) : sendForcedSetupUserHome(true);
});
Since the swap is dispatched inside the listener, useLinking sees the state change and doesn't roll back. It works the same whether browser back arrives as GO_BACK or as RESET (resetRoot), because we never replay the original action. The onboarding handoff gets the same fix through its existing helper. Voluntary setup from Settings > Security, the USD bank account and Xero flows never enter the listener.
I reproduced it live on dev web (staging) with the real 2FA setup and verified the fix: click outside → Home, browser back → Home with no blank page, second back stays on Home, "Got it" still goes Home, and voluntary setup still closes onto Security. In DynamicSuccessPageTest I added cases for a root goBack and a root reset (forced flow), the onboarding handoff, the helper's own dismiss not being blocked, and voluntary setup not being blocked. The forced ones fail on main and pass with the change.
Each video does the setup twice: first exit by clicking outside the RHP, second by browser back.
https://github.com/user-attachments/assets/0c83b222-0925-48ea-812d-1cfb74cb2384
https://github.com/user-attachments/assets/fa7308fe-b5ce-4212-8a6b-9ef82f679ccf
What alternative solutions did you explore? (Optional)
- Block the removal and call the helper as it is (#106178): rollback race on browser back described above.
- Reveal Home under the RHP when the success page mounts: on wide, Home shows behind the RHP early, and it doesn't cover the onboarding handoff where
openAppis deferred. - Open the overlay on Home again: that's what 2f529353b95 moved away from (half-loaded Home behind the modal).
🚨 Edited by proposal-police: This proposal was edited at 2026-11-09 06:23:17 UTC.
Proposal
Please re-state the problem that we are trying to solve in this issue.
After the required 2FA setup, "Got it" and the header arrow on the success RHP send the user Home, but Android back, browser back and clicking outside the RHP land on Account > Security.
What is the root cause of that problem?
There are two layers here. The first one explains the bug, the second one explains why blocking the removal (what #106178 does) gives the navigation and blank page bugs.
1. Home is only put under the RHP by two buttons
The require-2FA overlay opens setup with Settings > Security as the base under the RHP, on purpose (2f529353b95 moved it back from Home so a half-loaded Home isn't shown behind the modal):
https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/src/pages/RequireTwoFactorAuthenticationOverlay.tsx#L116-L119
The only thing that swaps Security for Home is revealRouteBeforeDismissingModal(ROUTES.HOME) inside sendForcedSetupUserHome / completeForcedOnboarding2FAHandoff, and only goBack and onButtonPress call them:
https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx#L82-L98
Android back, the overlay press (navigation.goBack()) and browser back (useLinking popstate) all remove the RHP straight from the root stack. The only listener on that removal just clears 2FA data:
https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/src/libs/Navigation/AppNavigator/Navigators/RightModalNavigator.tsx#L328-L335
So the RHP closes onto the Security base that is still there.
2. The Home swap is async, but the removal has to be answered in the same turn
The natural fix is to catch the removal on the success screen, preventDefault() it and call the same helper. That's #106178 and most proposals here, including my first version. It breaks because the reveal doesn't touch navigation state in that turn. Its route swap runs in a requestAnimationFrame and the dismiss in a second one:
https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/src/libs/Navigation/Navigation.ts#L1231-L1236
On browser back, the browser has already moved to the Security entry when beforeRemove fires. React Navigation's linking then checks whether the listener prevented the removal without dispatching anything in the same call. If so, it rolls the browser back with an async history.go(+1) (useLinking.tsx#L335-L376):
if (actionChangedState) {
pendingPopStateDeltaRef.current = pendingDelta;
} else if (removePrevented) {
rollbackHistory();
}
With the reveal deferred, actionChangedState is false, so the rollback starts. Then the swap and DISMISS_MODAL land while that history.go is still in flight, and the linking sync calls history.go/replaceState again. useLinking warns about this exact case (L680-L681): the URL and the navigation state end up out of sync, and that's the blank page. In #106178 it is even later, because the callback only sets state and the reveal starts from a useEffect after the next render. And usePreventRemove only sees a flag change on the next render, so the variants that flip a ref inside the callback can also block the helper's own DISMISS_MODAL.
So the real problem is that the forced exit isn't tied to the screen being removed, and the only Home swap we have can't run inside that removal.
What changes do you think we should make in order to solve the problem?
Keep the existing helpers as the single exit path, and let them do the swap (frame 1 of the reveal) synchronously when they are called from the removal event. The dismiss stays on the next frame like today.
-
Navigation.revealRouteBeforeDismissingModal: add ashouldRevealImmediatelyoption. Move the body of the firstrequestAnimationFrameinto a local function. When the option is set, call it right away instead of inside the rAF. Everything else stays the same: the pre-mount handling, the inner rAF that dispatchesDISMISS_MODAL, andafterTransition. -
DynamicSuccessPage:- add
isLeavingForcedFlowRef, set it totrueat the top ofsendForcedSetupUserHomeandcompleteForcedOnboarding2FAHandoff, so their ownDISMISS_MODALpasses through and a second back press can't start another reveal - both helpers take
shouldRevealImmediatelyand pass it to the reveal - listen to the removal with our existing
useBeforeRemove:
- add
useBeforeRemove((e) => {
if (isLeavingForcedFlowRef.current || !(shouldReturnToOnboardingAfter2FA || isForcedSetupFlow)) {
return;
}
e.preventDefault();
if (shouldReturnToOnboardingAfter2FA) {
completeForcedOnboarding2FAHandoff(true);
return;
}
sendForcedSetupUserHome(true);
});
Why this works for all three exits:
REPLACE_FULLSCREEN_UNDER_RHPis dispatched inside the listener, so linking seesactionChangedStateand doesn't roll the browser back. There's no asynchistory.goracing the reveal, so no blank page.- The same
REPLACE_FULLSCREEN_UNDER_RHP→DISMISS_MODALpair as "Got it" runs. That's the pair the root history extension tracks to keep browser history right after a reveal (addRootHistoryRouterExtensionUtils.ts#L98-L124 and #L142-L165), and the dismiss keeps its own frame, so the slide animation is the same as "Got it". - It doesn't matter whether browser back reaches the screen as a
GO_BACKor as aRESET(useLinking picksresetRootwhen it's not a plain pop). We cancel it either way and run our exit. We don't replay it, because replaying aRESETwould re-apply the old browser record, which still has Security in it. - The onboarding handoff gets the same fix for free. Today the same three exits drop that user on Security without resuming onboarding.
Voluntary setup from Settings > Security, the USD bank account flow and the Xero flow never enter the listener, because both flags require forceSetup. Callers that don't pass the new option (expense submit, share etc.) keep the two-frame reveal exactly as today.
What specific scenarios should we cover in automated tests?
In DynamicSuccessPageTest, with the success screen nested in a modal above a base route (real react-navigation):
- forced flow: a root
goBack()(Android back / overlay press) callsrevealRouteBeforeDismissingModal(ROUTES.HOME, {shouldRevealImmediately: true})once and the RHP ends up closed - forced flow: a root
reset(browser back viaresetRoot) does the same - forced flow: "Got it" and the header arrow still reveal Home once, with no immediate flag, and their dismiss isn't blocked
- forced onboarding handoff: a root
goBack()resumes onboarding once - voluntary Settings > Security setup: removal isn't prevented and nothing reveals Home
In NavigationTest: with shouldRevealImmediately, REPLACE_FULLSCREEN_UNDER_RHP is dispatched synchronously and DISMISS_MODAL on the next frame.
What alternative solutions did you explore? (Optional)
usePreventRemove/useBeforeRemovethat cancels the removal and then calls the current helper (#106178). It has the history rollback race above on browser back, and withusePreventRemovethe helper's own dismiss can be blocked by the stale flag.- Swap Home in synchronously, don't cancel, and let React Navigation replay the original action on the new state. That works for
GO_BACK, but a replayedRESETfrom browser back re-applies the Security record. It also leaves the reveal the history extension armed without itsDISMISS_MODAL, and needs a second copy of the handoff logic in the listener. - Swap Home under the RHP when the success page mounts. It doesn't cover the onboarding handoff, where Home isn't loaded yet because
openAppis deferred until the user leaves the page. On wide it also shows Home behind the RHP before the user leaves. - Go back to Home as the overlay's base route. It fixes every exit, but it's the half-loaded Home that 2f529353b95 reverted.
- Patch each exit separately (
useAndroidBackButtonHandler+ a 2FA case inhandleOverlayPress). Browser back still isn't covered, and it's the same per-button approach that left these gaps in the first place.
Proposal
Please re-state the problem that we are trying to solve in this issue.
When a workspace requires 2FA, a member without 2FA is shown the required-2FA screen and enters the setup flow from there. After finishing setup, pressing the Android system back button on the 2FA success page lands the user on Account > Security instead of Home. On web, the browser back button and clicking outside the RHP do the same.
What is the root cause of that problem?
The "send the forced-setup user Home" logic lives only in the success page's own back handler, and that handler is wired exclusively to the header back arrow.
When the required-2FA screen starts the setup, it first navigates to the Security settings page with a forceSetup=true marker, so that page becomes the full-screen route sitting underneath the 2FA RHP:
https://github.com/Expensify/App/blob/0265933d583f17d548e01308a2666789e0be0abd/src/pages/RequireTwoFactorAuthenticationOverlay.tsx#L116-L119
On the success page, goBack detects this forced flow and redirects Home via sendForcedSetupUserHome:
https://github.com/Expensify/App/blob/0265933d583f17d548e01308a2666789e0be0abd/src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx#L82-L113
But that goBack is only passed down as onBackButtonPress, which the wrapper attaches solely to HeaderWithBackButton — the header's back arrow:
https://github.com/Expensify/App/blob/0265933d583f17d548e01308a2666789e0be0abd/src/pages/settings/Security/TwoFactorAuth/TwoFactorAuthWrapper.tsx#L87-L91
Every other way of leaving the success page never calls that handler. The Android system back button and the browser back button dispatch a plain navigation pop, and clicking outside the RHP calls the overlay press handler, which also just calls navigation.goBack():
https://github.com/Expensify/App/blob/0265933d583f17d548e01308a2666789e0be0abd/src/libs/Navigation/AppNavigator/Navigators/RightModalNavigator.tsx#L250-L262
A plain pop removes the 2FA RHP and reveals whatever full-screen route is underneath — which, in the forced flow, is the Security settings page that the required-2FA screen pushed. So the user lands on Account > Security instead of Home. This is a leftover gap from the change that introduced the Home redirect (it only covered the header arrow and the confirm button, not system/browser back or outside clicks).
What changes do you think we should make in order to solve the problem?
In DynamicSuccessPage, intercept the screen's removal with usePreventRemove from @react-navigation/native, active while the flow needs a custom exit (the forced-setup flow, and the forced-onboarding handoff which has the same divergence). When a removal is prevented for the first time, run the exact same goBack logic the header arrow uses, so the user is sent Home with the same cleanup. Keep a ref flag marking that the redirect has started; when the redirect itself later dismisses the modal, the prevented action is re-dispatched on the root navigation ref so the dismissal completes. This re-dispatch-through-the-root pattern already exists in the codebase for the same reason:
https://github.com/Expensify/App/blob/0265933d583f17d548e01308a2666789e0be0abd/src/pages/settings/Profile/CustomStatus/VacationDelegateMissingWorkspacesPage/index.tsx#L95-L104
With this, the Android system back button, the browser back button, and clicking outside the RHP all take the same path as the header back arrow: the user lands on Home, and the existing 2FA cleanup still runs through the modal's removal listener. Platforms outside the forced flows are untouched because the guard is inactive there, so the regular Settings > Security entry keeps its current behavior.
Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/105693-2fa-success-system-back?expand=1
What alternative solutions did you explore? (Optional)
Making the required-2FA screen keep Home as the underlying route instead of navigating to the Security settings page first. Rejected: the forceSetup marker on the Security route is how the success page recognizes the forced flow (route params survive the account data reset during verification), and keeping Settings > Security behind the setup was a deliberate part of the original design.
Handling it in the right-modal navigator's removal listener for the 2FA stack. Rejected: that listener is a generic cleanup hook without access to the success page's flow detection (route params and onboarding state), so the redirect decision cannot be made correctly there.
