[Due for payment 2026-11-30] [$250] Dev - iOS - Expense - Error parsing URL when open view hold expense
If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.
Version Number:
Reproducible in staging?: Needs Reproduction (Unable to reproduce)
Reproducible in production?: Needs Reproduction
If this was caught during regression testing, add the test name, ID and link from BrowserStack:
Email or phone of affected tester (no customers):
Logs: https://stackoverflow.com/c/expensify/questions/4856
Expensify/Expensify Issue URL:
Issue reported by: @paulnjs
Slack conversation (hyperlinked to channel name): #Open source
Action Performed:
Precondition:
- User A invite user B into a workspace
- User A set user B as approver
- User A submit an expense in workspace
- Login as user B
- Select expense user A just submitted
- Tap on More > Split > confirm to split expense
- Select one of 2 split expense and hold it
- Back and approve only unheld expense
- Back and select held expense
- Reopen the app
Expected Result:
No error appear in Console Error
Actual Result:
In Console Error appear Error parsing URL: TypeError: Invalid URL
Workaround:
Unknown
Platforms:
Select the officially supported platforms where the issue was reproduced:
- [ ] Android: App
- [ ] Android: mWeb Chrome
- [x] iOS: App
- [ ] iOS: mWeb Safari
- [ ] iOS: mWeb Chrome
- [ ] Windows: Chrome
- [ ] MacOS: Chrome / Safari
Screenshots/Videos
https://github.com/user-attachments/assets/1d143142-0ecc-4adf-812c-be4a844cf8ed
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022122823205914637295
- Upwork Job ID: 2122823205914637295
- Last Price Increase: 2026-11-19
Issue Owner
Current Issue Owner: @mallenexpensify
Triggered auto assignment to Contributor-plus team member for initial proposal review - @mukhrr (External)
Job added to Upwork: https://www.upwork.com/jobs/~022122823205914637295
Issue Analysis
⚠️ Preliminary analysis — low confidence in the issue-specific root cause.
What is confirmed
The exact error comes from getPathFromURL: it calls new URL(url) without a base, catches invalid input, and logs the reported message. This diagnostic alone does not establish an expense or navigation failure.
Two paths could explain its appearance after reopening:
- Launch URL:
NavigationRootparses a nonempty initial URL. The saved expense route is restored separately, so a relative saved route is not sufficient to explain this error. - Rendered report link:
AnchorRendererclassifies hyperlinks during rendering, reaching the same parser without a tap. Partial approval creates a system message containing a report link, making this a relevant alternative.
Validation and limitations
The URL and navigation unit suites passed: 28 tests. The reported iOS flow was not reproduced, and the issue lacks the affected build version, failing URL, and JavaScript stack.
An environment-URL initialization race was considered, but normal development-build startup ordering argues against it. It is not a verified cause.
Evidence needed before recommending a fix
Capture the first error’s complete stack and failing URL, redacting credentials and sensitive query values. Also record the build version and whether “reopen” means foregrounding, force-quitting, or reloading.
- A
NavigationRootcaller points toward launch input. - An
AnchorRenderer/Linkcaller points toward rendered report content.
Changing split/hold logic or suppressing the error is not justified yet.
Possibly related issues
These share the partial-approval flow, but neither establishes a shared URL-parsing cause:
- Expense — Both approved and held expenses’ total is shown after approving
- Reports — Approved expense shown on same report as a held one after approving
Next Steps: Provide the failing URL and caller stack to distinguish the two paths and verify a targeted fix.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01f6ba4c6dde3d0fbb
Proposal
Please re-state the problem that we are trying to solve in this issue.
On iOS/native, reopening the app when viewing a held split expense produces Error parsing URL: TypeError: Invalid URL in the console.
What is the root cause of that problem?
- In
src/libs/Navigation/helpers/getReportURLForCurrentContext.ts(andsrc/libs/ReportActionsUtils.ts),environmentURLis declared as an uninitialized module-scoped variable:let environmentURL: string; getEnvironmentURL().then((url: string) => (environmentURL = url)); - On native platforms,
getEnvironment()insrc/libs/Environment/getEnvironment/index.native.tsis asynchronous because it callsbetaChecker.isBetaBuild(). - When the app reopens on the held expense report, the screen and its report actions mount before this promise resolves.
- When
CreatedReportForUnapprovedTransactionsActionrenders (created when approving the unheld split expense), it invokesgetReportURLForCurrentContext(originalID). - Since
environmentURLis stillundefined, it generates a malformed URL string"undefined/r/<reportID>"inside the anchor HTML<a href="undefined/r/...">. - When
<RenderHTML>parses this element,AnchorRenderer.tsxpasses the href togetInternalNewExpensifyPath(attrHref)->Url.getPathFromURL("undefined/r/..."). new URL("undefined/r/...")insrc/libs/Url.tsthrowsTypeError: Invalid URL, which is caught and logged to the console viaconsole.error('Error parsing URL:', error).
What changes do you think we should make in order to solve the problem?
- In
src/libs/Navigation/helpers/getReportURLForCurrentContext.ts:- Initialize
environmentURLwithCONST.NEW_EXPENSIFY_URLas a default synchronous fallback so it is neverundefined:let environmentURL: string = CONST.NEW_EXPENSIFY_URL; getEnvironmentURL().then((url: string) => (environmentURL = url)); - In
getReportURLForCurrentContext, ensure a safe fallback:const baseUrl = environmentURL || CONST.NEW_EXPENSIFY_URL;
- Initialize
- Apply the same default initialization (
let environmentURL: string = CONST.NEW_EXPENSIFY_URL;) tosrc/libs/ReportActionsUtils.tsandsrc/libs/ModifiedExpenseMessage.tsto prevent identical race conditions across system action messages. - In
src/libs/Url.ts(getPathFromURL):- Provide a safe base URL
new URL(url, CONST.NEW_EXPENSIFY_URL)so relative paths and routes don't throw an invalid URL error, and guard against strings starting withundefined.
- Provide a safe base URL
What alternative solutions did you explore? (Optional)
Making getReportURLForCurrentContext asynchronous, but initializing environmentURL with CONST.NEW_EXPENSIFY_URL is much cleaner and eliminates asynchronous rendering flickers in report actions.
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
@MelvinBot pls leave a proposal
Proposal
What is the root cause of that problem?
The attached recording contains more specific evidence than the issue description: near the end, LogBox shows Invalid URL: undefined/r/4945629927818497, with hasSameExpensifyOrigin → getInternalExpensifyPath in the call stack. This points to a malformed rendered report link, not simply a relative route restored at launch.
CreatedReportForUnapprovedTransactionsAction builds HTML using getCreatedReportForUnapprovedTransactionsMessage, which calls getReportURLForCurrentContext. That helper declares let environmentURL: string and assigns it only inside getEnvironmentURL().then(...). Any synchronous call before that callback runs therefore generates undefined/r/<reportID>. AnchorRenderer classifies this href during rendering, without a tap.
On native, environment resolution returns a promise; non-dev/non-adhoc builds can additionally wait for betaChecker.isBetaBuild(). Even an immediately resolved promise does not run its .then callback synchronously. The source therefore permits the exact malformed value shown in the recording. I would verify the precise early-render timing with a deferred-environment test and an iOS replay, rather than claim to have reproduced it already.
Importantly, Url.ts already catches the exception. Its console.error("Error parsing URLs:", error) produces the reported development LogBox; this is not evidence of an uncaught application crash.
What changes do you think we should make in order to solve the problem?
-
Fix generation first. Initialize
environmentURLsynchronously fromCONST.NEW_EXPENSIFY_URLingetReportURLForCurrentContext.ts, retaining the asynchronous update to the actual environment. Normalize trailing slashes when joining the base and route so the fallback cannot introduce//r/. Keep the helper synchronous and preserve report IDs, search routes andbackTobehavior. -
Cover the same initialization defect at the other producers. Apply the same fallback to the module-level
environmentURLvariables inReportActionsUtils.tsandModifiedExpenseMessage.ts. This follows the existingEnvironmentContextProviderdefault, rather than adding a new initialization mechanism. The fallback must not permanently replace the resolved environment; verify both early-link handling and subsequent dev/staging/adhoc/production links, including navigation in the current environment. -
Add narrow protection in
Url.ts. Before parsing, reject empty or non-absolute input inhasSameExpensifyOriginandgetPathFromURL, returning their existingfalseand empty-string results. These functions already usenew URL(value)without a base, so relative input is already rejected; the guard avoids an expected invalid-input exception and its render-time error logging. Retain exception handling for malformed absolute URLs and preserve existing valid-link classification. Do not apply this restriction to separate navigation helpers that intentionally accept relative routes.
Validation plan: defer getEnvironmentURL() and check generated links before/after resolution in all three producers; cover missing report IDs, trailing slashes, search/backTo, and environment switching. Test empty and undefined/r/... hrefs for the existing rejection results without console errors, plus valid internal/external links. Then repeat the two-account split → hold → partial approval → reopen flow on iOS. These checks are proposed, not claimed as already executed.
What alternative solutions did you explore? (Optional)
Making the report helper asynchronous would unnecessarily change synchronous rendering callers. Only suppressing the console error leaves broken links. Using new URL(value, CONST.NEW_EXPENSIFY_URL) is not a safe repair: it turns undefined/r/... into a valid-looking internal path. Fixing the producer, with a narrow parser guard as defense in depth, avoids that misclassification.
Proposal
Please re-state the problem that we are trying to solve in this issue.
On a native iOS Dev build, after splitting an expense, holding one of the split expenses, approving only the unheld expense, opening the held expense, and reopening the app, the console logs Error parsing URL: TypeError: Invalid URL.
What is the root cause of that problem?
Approving only the unheld split expense creates a new report for the held expense and moves the held transaction there, adding a MOVED_TRANSACTION system action on the held expense thread (MovedTransactionAction.tsx -> getMovedTransactionMessage) and a CREATED_REPORT_FOR_UNAPPROVED_TRANSACTIONS action on the new report (CreatedReportForUnapprovedTransactionsAction.tsx -> getCreatedReportForUnapprovedTransactionsMessage). Both build an <a href="${reportUrl}"> anchor via getReportURLForCurrentContext(reportID) (src/libs/Navigation/helpers/getReportURLForCurrentContext.ts:8-9,18-25):
let environmentURL: string;
getEnvironmentURL().then((url: string) => (environmentURL = url));
Why this specifically triggers on native iOS Dev upon reopening (even though getEnvironment/index.native.ts:18-22 resolves CONST.ENVIRONMENT.DEV synchronously without calling betaChecker.isBetaBuild()):
- Deferred module evaluation via Re.Pack inline-requires (
config/repack/cjs-inline-requires-loader.mjs): On native iOS/Android builds,inlineInteropRequiresPlugindefers default ES imports (import getReportURLForCurrentContext from './Navigation/helpers/getReportURLForCurrentContext') down to their first call site instead of hoisting them at app startup (unlike web ESM). - Synchronous cold-start render precedes the
.then()microtask: When reopening the app ontolastVisitedPath(NavigationRoot.tsx:185, the held expense thread),<MovedTransactionAction>(or<CreatedReportForUnapprovedTransactionsAction>) renders and triggers the inlinedrequire('./Navigation/helpers/getReportURLForCurrentContext')for the first time inside synchronous React render. Even thoughgetEnvironment()callsresolve(CONST.ENVIRONMENT.DEV)synchronously insidenew Promise(...), JavaScript always enqueues.then((url) => (environmentURL = url))as a microtask after the current synchronous render call stack completes. "undefined/r/<reportID>"reachesAnchorRenderer->Url.getPathFromURL: During that first synchronous call,environmentURLisundefined, sogetReportURLForCurrentContextreturns"undefined/r/<reportID>".<RenderHTML>immediately invokesAnchorRenderer.tsx:48, which callsgetInternalNewExpensifyPath("undefined/r/<reportID>")(src/libs/actions/Link.ts:144) ->Url.getPathFromURL("undefined/r/<reportID>")(src/libs/Url.ts:20), throwingTypeError: Invalid URLand loggingconsole.error('Error parsing URL:', error). Furthermore, when the microtask later mutates the module-scopedlet environmentURL, React does not re-render<MovedTransactionAction>or<CreatedReportForUnapprovedTransactionsAction>.
What changes do you think we should make in order to solve the problem?
- Provide a single synchronous + async-updated source of truth in
src/libs/Environment/Environment.ts: ExportgetCurrentEnvironmentURL(): stringfromEnvironment.ts, returningresolvedEnvironmentURLoncegetEnvironment()settles, and synchronously computingENVIRONMENT_URLS[((Config?.ENVIRONMENT ?? CONST.ENVIRONMENT.DEV).trim() || CONST.ENVIRONMENT.DEV) as Environment] ?? CONST.NEW_EXPENSIFY_URLbefore the microtask runs (so Dev immediately getshttps://dev.new.expensify.com:8082, Staging/AdHoc gethttps://staging.new.expensify.com, QA getshttps://qa.new.expensify.com, and Production/TestFlight getshttps://new.expensify.comuntilbetaCheckersettles). - Update
getReportURLForCurrentContextandEnvironmentProvider:- In
src/libs/Navigation/helpers/getReportURLForCurrentContext.ts, remove the uninitializedlet environmentURL: stringmodule state and accept an optionalenvironmentURLOverride?: string, defaulting togetCurrentEnvironmentURL(). - In
src/components/EnvironmentContextProvider/index.tsx, initializeenvironmentURLstate lazily viauseState(() => getCurrentEnvironmentURL())while keeping theuseEffectupdate for native TestFlight (betaChecker.isBetaBuild()).
- In
- Pass reactive
useEnvironment().environmentURLfrom the action components:- In
MovedTransactionAction.tsxandCreatedReportForUnapprovedTransactionsAction.tsx, readconst {environmentURL} = useEnvironment()and forward it throughgetMovedTransactionMessage/getCreatedReportForUnapprovedTransactionsMessageintogetReportURLForCurrentContext(reportID, environmentURL). That ensures both components render a valid environment-matched URL on the very first synchronous frame AND re-render ifEnvironmentProviderpromotes a TestFlight build fromproductiontostaging.
- In
- Add unit tests covering synchronous cold-require of
getReportURLForCurrentContexton Dev (https://dev.new.expensify.com:8082), Staging, and TestFlight promotion, verifyingAnchorRenderer/Url.getPathFromURLlogs zero console errors.
What alternative solutions did you explore? (Optional)
- Defaulting
let environmentURL = CONST.NEW_EXPENSIFY_URLingetReportURLForCurrentContext.ts: AvoidsTypeError: Invalid URL, but bakes the Production origin (https://new.expensify.com) into Dev (https://dev.new.expensify.com:8082) and Staging anchors on initial render, and mutating a module variable in.then()never triggers a React re-render. - Passing a base URL (
new URL(url, CONST.NEW_EXPENSIFY_URL)) inUrl.getPathFromURL: BreaksUrl.getPathFromURL's contract and existing unit tests (tests/unit/UrlTest.ts:21-35), where non-URL strings such as'testRareTLDs.beer'and'[email protected]'must return''rather than being parsed as relative paths.
@MelvinBot pls leave a proposal
@MelvinBot is kinda unresponsive and I think this is bit tricky issue.
Pls include before/after videos
🆘 C+ Help Wanted
Proposal
Please re-state the problem that we are trying to solve in this issue.
On native, after a partial approval moves the held expense to a new report, reopening the app on that report logs Error parsing URL(s): TypeError: Invalid URL. The "created this report for any held expenses from " message is rendered with href="undefined/r/<reportID>". The LogBox at the end of the attached video shows exactly that: Invalid URL: undefined/r/4945629927818497.
What is the root cause of that problem?
The href is built by getReportURLForCurrentContext, which reads a module-level environmentURL that only gets filled by an async .then when the module is evaluated
https://github.com/Expensify/App/blob/5f3ba46ff8c42234c2d5c2d153d555623aaeb15d/src/libs/Navigation/helpers/getReportURLForCurrentContext.ts#L8-L9
https://github.com/Expensify/App/blob/5f3ba46ff8c42234c2d5c2d153d555623aaeb15d/src/libs/Navigation/helpers/getReportURLForCurrentContext.ts#L19-L25
The async .then alone doesn't explain it though. On a dev build getEnvironment resolves right away, and by the time a report renders the app has been running for seconds. ReportActionsUtils has the exact same pattern (ReportActionsUtils.ts#L176-L177) and its links are fine. The difference is when the module gets evaluated.
On native, app source goes through the inline-requires loader, so every import becomes a require() at its first use site, and a module is only evaluated the first time something calls into it
https://github.com/Expensify/App/blob/5f3ba46ff8c42234c2d5c2d153d555623aaeb15d/config/repack/rspack.config.mjs#L99-L108
ReportActionsUtils is used everywhere, so it's evaluated at boot and its .then has long resolved. But the helper is only used inside function bodies of ReportActionsUtils/ReportUtils for a handful of rare messages, so after a cold start nothing has touched it yet, and it gets evaluated inside its very first call, during render:
CreatedReportForUnapprovedTransactionsActionrenders and callsgetCreatedReportForUnapprovedTransactionsMessagehttps://github.com/Expensify/App/blob/5f3ba46ff8c42234c2d5c2d153d555623aaeb15d/src/components/ReportActionItem/CreatedReportForUnapprovedTransactionsAction.tsx#L22-L26- that calls
getReportURLForCurrentContext(reportID), whichrequires the helper for the first time. Its top level schedulesgetEnvironmentURL().then(...)(can only run on a later microtask), then the function returns synchronously withenvironmentURL === undefined→undefined/r/<reportID>https://github.com/Expensify/App/blob/5f3ba46ff8c42234c2d5c2d153d555623aaeb15d/src/libs/ReportActionsUtils.ts#L5942-L5948 AnchorRendererclassifies the href while rendering (no tap needed) throughgetInternalNewExpensifyPath/getInternalExpensifyPath, which callnew URL('undefined/r/<id>')ingetPathFromURLandhasSameExpensifyOrigin, which throw and log https://github.com/Expensify/App/blob/5f3ba46ff8c42234c2d5c2d153d555623aaeb15d/src/components/HTMLEngineProvider/HTMLRenderers/AnchorRenderer.tsx#L49-L50 https://github.com/Expensify/App/blob/5f3ba46ff8c42234c2d5c2d153d555623aaeb15d/src/libs/Url.ts#L18-L43
The bad href also sticks. React Compiler memoizes the component output on its inputs (originalID, originalReport, action, translate), and none of them depend on the environment URL, so nothing re-renders when the .then resolves later. The link stays unrecognized as internal (onLinkPress is undefined) until some unrelated prop changes.
That's also why web doesn't show it: rsbuild evaluates the import graph eagerly at boot, long before any report renders.
I confirmed the ordering by running the repo's real config/repack/cjs-inline-requires-loader.mjs on a 4-module copy of this chain (component → ReportActionsUtils → helper → Environment, with the env promise resolving immediately like on dev):
[eval] ./Component
-- component loaded; first render:
[eval] ./ReportActionsUtils
[eval] ./getReportURL
[eval] ./Env
first render : <a href="undefined/r/123">r</a>
next tick : <a href="https://dev.new.expensify.com:8082/r/123">r</a>
What changes do you think we should make in order to solve the problem?
Stop reading the lazily filled module variable at render time and take the URL from EnvironmentProvider, which resolves it once on app mount and re-renders its consumers when it changes (EnvironmentContextProvider/index.tsx#L81-L84). That's the same pattern AnchorRenderer, MoneyRequestView and TransactionPreviewContent already use.
getReportURLForCurrentContexttakes the base URL as an optional param and only falls back to the module value when a caller doesn't pass one:
function getReportURLForCurrentContext(reportID: string | undefined, currentEnvironmentURL = environmentURL): string {
if (!reportID) {
return `${currentEnvironmentURL}/r/`;
}
...
return `${currentEnvironmentURL}/${relativePath}`;
}
getCreatedReportForUnapprovedTransactionsMessageforwards it:
function getCreatedReportForUnapprovedTransactionsMessage(
reportID: string | undefined,
reportName: string,
isReportDeleted: boolean,
translate: LocalizedTranslate,
currentEnvironmentURL?: string,
): string {
if (reportID === undefined) {
return '';
}
const reportUrl = getReportURLForCurrentContext(reportID, currentEnvironmentURL);
return translate('reportAction.createdReportForUnapprovedTransactions', reportUrl, reportName, reportID, isReportDeleted);
}
CreatedReportForUnapprovedTransactionsActionreads it from the hook:
const {environmentURL} = useEnvironment();
const htmlContent = `<comment><muted-text>${getCreatedReportForUnapprovedTransactionsMessage(originalID, reportName, isOriginalReportDeleted(action, originalReport), translate, environmentURL)}</muted-text></comment>`;
environmentURL is now one of the compiler's memo inputs, so the message always has a real origin and refreshes if the provider value ever changes. The context menu copy path for the same action (ContextMenuActions.tsx#L1642-L1647) can keep the fallback, since it runs on a user tap long after the value resolved.
Tests: a unit test for getReportURLForCurrentContext that passes an explicit URL while the module value is still unset, and a render test for CreatedReportForUnapprovedTransactionsAction that asserts the anchor href starts with the environment URL and console.error isn't called.
Branch with the change: main...David-2002065:poc/107179-env-url
I tested it on iOS with the same flow as the issue (submit, hold one expense, approve only the other, then reopen the app on the held report).
Before, the same Invalid URL: undefined/r/<reportID> console error on every cold start:
https://github.com/user-attachments/assets/8af0c482-501a-490a-a1b0-b7fa25a2eadd
After, no console error, and the link in the message opens the approved report:
https://github.com/user-attachments/assets/b0c219ca-945a-4ab5-baf0-ff27a005f848
What alternative solutions did you explore? (Optional)
- Fix it at the source for every caller:
getEnvironmentalready caches the resolved value in a module variable, and it's resolved long before any report renders (the API root waits on it). Expose a syncgetCachedEnvironmentURL()fromEnvironment.tsthat returnsENVIRONMENT_URLS[cachedEnvironment], and havegetReportURLForCurrentContextread it instead of its own.thencopy. That also covers the other messages built through this helper inReportUtils(moved report, unreported/self-DM links) that have the same first-call shape. - Defaulting the module variable to
CONST.NEW_EXPENSIFY_URL, as a couple of the proposals above suggest. It removes the log, but on dev/staging the first rendered link points at production and stays that way because of the memoization above, so the ordering problem is still there. - Passing a base to
new URL(url, base)or adding an absolute-URL guard inUrl.ts. That only hides the symptom, the message would still carry a brokenundefined/r/...link, so I'd keep the parsers strict and fix the producer.
Proposal
Please re-state the problem that we are trying to solve in this issue.
On iOS, after a partial approval moves a held split expense into a new report, reopening the app on that report logs Error parsing URL: TypeError: Invalid URL.
What is the root cause of that problem?
The rendered pixel is the "created this report for any held expenses from <report name>" system message. CreatedReportForUnapprovedTransactionsAction builds an <a href> through getCreatedReportForUnapprovedTransactionsMessage. That function calls getReportURLForCurrentContext, which reads a module-level variable that only a promise fills in:
https://github.com/Expensify/App/blob/e31aac87c46acffbe1ece5decf13fac0014ea744/src/libs/Navigation/helpers/getReportURLForCurrentContext.ts#L8-L9
Native bundles defer every import until it's first used. Our Re.Pack loader (wired for src/ here) rewrites the import in ReportActionsUtils into an inline require("./Navigation/helpers/getReportURLForCurrentContext") at the call site. I ran the loader on the file to confirm this. So the helper module is evaluated inside the first call. Its .then() can only run after that call has already returned `${undefined}/r/<id>`. This doesn't depend on whether getEnvironment() is slow. Even on Dev, where it resolves immediately, the first caller loses.
On a cold start that lands on the held-expense report, this action is the first thing that needs a report URL, so it gets undefined/r/<id>. RenderHTML then runs AnchorRenderer → getInternalNewExpensifyPath → getPathFromURL. That calls new URL('undefined/r/<id>'), which throws, and the catch block logs the reported error. Nothing re-renders the action when the variable settles later, so the broken href stays on screen. Jest evaluates imports eagerly, which is why no existing test catches this.
What changes do you think we should make in order to solve the problem?
Fix it at the render layer. The component should use the environment URL it already has from React, not a module variable whose readiness it can't observe. EnvironmentProvider holds a valid URL from the first render (it defaults to NEW_EXPENSIFY_URL) and re-renders consumers when the real URL resolves.
// CreatedReportForUnapprovedTransactionsAction (same for CreateHarvestReportAction, which has the identical shape)
const {environmentURL} = useEnvironment();
getCreatedReportForUnapprovedTransactionsMessage(originalID, reportName, isDeleted, translate, environmentURL)
// getReportURLForCurrentContext(reportID, currentEnvironmentURL?)
const environmentURL = currentEnvironmentURL ?? cachedEnvironmentURL ?? CONST.NEW_EXPENSIFY_URL;
The parameter is optional, so the non-render callers (ReportUtils, computeReportName, the copy-to-clipboard path) are unchanged. They also can no longer produce undefined/.... The fix doesn't depend on timing: every render produces a valid href whether or not the promise has settled, and the link updates to the resolved environment because it now comes from context.
I added tests/ui/CreatedReportForUnapprovedTransactionsActionTest.tsx. It renders the action with real HTMLEngineProvider + EnvironmentProvider while getEnvironmentURL() is still pending, then resolves it to the dev URL and taps the link.
- On
mainit fails with exactlyError parsing URL: [TypeError: Invalid URL: undefined/r/67890]. With the patch it passes, andopenLinkreceiveshttps://dev.new.expensify.com:8082/r/67890. - Guard suites (
ReportUtilsTest,ReportActionsUtilsTest,ReportActionItemTest,LinkTest,UrlTest,EnvironmentContextTest,ContextMenuActionsCopyMessageTest,MentionReportRendererTest): 2779/2779 pass before and after, plus the 1 new test. - Typecheck, lint, the React Compiler compliance check and cspell are all clean.
This is code and test evidence only. I couldn't get the iOS app running on my machine, so I haven't reproduced it on a device.
What alternative solutions did you explore? (Optional)
Make getPathFromURL tolerate relative input (new URL(url, base)). Rejected: this hides the symptom at the parser, but the anchor still points at undefined/r/<id>. Tapping it then resolves to a path under a fake undefined segment, not to the report.
Await the environment before mounting NavigationRoot. Rejected: it delays boot for every user to fix one module. It also doesn't help the deferred-import case, because the helper module still evaluates on its first call, after any such gate.
Defaulting the module variable to production removes the log, but I tried it against the same test: on dev/staging the mounted link stays at https://new.expensify.com//r/67890. Because of that, openLink doesn't see a same-origin link and won't open the report inside the app.
Proposal
Please re-state the problem that we are trying to solve in this issue.
After a cold start (reopen the app) and opening the held expense, the console logs Error parsing URL: TypeError: Invalid URL. The system message link that is rendered on that screen was built with an undefined origin.
What is the root cause of that problem?
The report URL helper reads its origin from a module variable that is filled in asynchronously, and it is read before it is filled in.
getReportURLForCurrentContextkeepsenvironmentURLin an uninitialized module variable and fills it in from a promise callback at module load: getReportURLForCurrentContext.ts#L8-L9. It then builds the link as${environmentURL}/r/<reportID>(#L19-L25, and #L74 in Search).- Native bundles defer every
require()to its first use site (inline requires: cjs-inline-requires-loader.mjs#L1-L11, wired in rspack.config.mjs#L108). So this module is only evaluated the first time the helper is called, which happens during render. Even on dev, where getEnvironment resolves at once, the.thenis a microtask, so that first call has already returned"undefined/r/<id>". - The held-expense screen is exactly where that first call happens. Approving only the unheld expense moves the held one to a new report, and its system messages build their link through this helper:
- "created this report for any held expenses from …": ReportActionsUtils.ts#L5941-L5947, rendered by CreatedReportForUnapprovedTransactionsAction.tsx#L26
- "moved this expense from/to …": ReportUtils.ts#L8690, rendered by MovedTransactionAction.tsx#L41
- the same helper also feeds the unreported, moved-report and harvest messages (ReportUtils.ts#L8718, #L8749, #L9197-L9198, #L9293, ReportActionsUtils.ts#L5928). So any of them can be the first caller after a reopen.
AnchorRendererclassifies every href by calling getInternalNewExpensifyPath / getInternalExpensifyPath. Both call Url.getPathFromURL, andnew URL("undefined/r/123")throws, givingconsole.error('Error parsing URL:').
Structural cause: this module was split out of ReportUtils in a97821906ab (refactor: extract getReportURLForCurrentContext to navigation helper, PR #75511). That refactor kept the "fill in later" module variable and assumed the module loads at boot, the way ReportUtils does. With inline requires, a small helper module loads at its first call instead. So the value is missing exactly once per app launch, which is why the bug needs "reopen the app" and is hard to reproduce. It is not just console noise. The bad href is classified as external, so tapping the link in that message does not navigate in-app.
What changes do you think we should make in order to solve the problem?
Give the module variable a valid initial value. Use the same default the app already uses for this exact gap: EnvironmentProvider starts from environmentURL: CONST.NEW_EXPENSIFY_URL until getEnvironmentURL() resolves.
// src/libs/Navigation/helpers/getReportURLForCurrentContext.ts
let environmentURL: string = CONST.NEW_EXPENSIFY_URL;
getEnvironmentURL().then((url: string) => (environmentURL = url));
CONST.NEW_EXPENSIFY_URL comes from the build's own NEW_EXPENSIFY_URL config (.env.staging → staging, .env.production → production). So even the first link points at the right NewDot origin, and it is always in NEW_EXPENSIFY_ORIGINS, so it is still treated as an internal link. Once the promise resolves, the code path is the same as today.
Regression safety: only the value seen before the promise resolves changes. That value was undefined before, so every caller listed above goes from a broken href to a valid one, and nothing else changes.
Why the obvious one-liners don't work
- Silencing
getPathFromURL(URL.canParse, or dropping theconsole.error) only hides the log. The href is stillundefined/r/<id>, soopenLinksends it toopenExternalLinkand the link stays broken. - Patching the held-expense components only fixes one caller. The helper has several callers (all listed in step 3), and whichever one renders first after a reopen hits the same bug.
Secondary (optional): ModifiedExpenseMessage.ts#L29-L30 uses the same uninitialized pattern and is also lazily loaded. Its rules links (#L253-L255, #L413) can hit the same error when a "changed … via workspace rules" message is the first one rendered. The same one-line default fixes it. That is not in the reported repro.
What alternative solutions did you explore? (Optional)
- Import the helper eagerly at boot so the promise resolves before first render. This is fragile. Inline requires defer it again as soon as the import is only used inside a function, and nothing enforces the order.
- Make the helper async / await
getEnvironmentURL(). Every caller builds translated HTML synchronously during render, including the derived report name in computeReportName.ts#L1011. That would change every call site to fix a value that is missing once per launch. - Re-import
environmentURLfromReportUtilsinstead of keeping a copy. That brings back the circular dependencya97821906abwas written to remove.
Proposal
Please re-state the problem that we are trying to solve in this issue.
On iOS, after splitting an expense, holding one of the splits, approving only the unheld expense, and then opening the held expense's thread, reopening the app logs a console error: Error parsing URL: TypeError: Invalid URL. The video shows the full message: Error parsing URLs: TypeError: Invalid URL: undefined/r/4945629927818497 — the app is trying to parse a link whose address literally starts with the string undefined.
What is the root cause of that problem?
The approve-only-unheld flow leaves a MOVED_TRANSACTION report action ("moved this expense from …") in the held expense's thread. That message's HTML — including the <a href> link to the originating report — is rebuilt on every render by getMovedTransactionMessage, which gets the link target from getReportURLForCurrentContext:
https://github.com/Expensify/App/blob/a66a788c1843dfefa4338d2499dfcb3b008d48dc/src/libs/ReportUtils.ts#L8690
getReportURLForCurrentContext builds that URL by interpolating a module-level environmentURL variable that is populated asynchronously, by a fire-and-forget promise started when the module is first evaluated:
https://github.com/Expensify/App/blob/a66a788c1843dfefa4338d2499dfcb3b008d48dc/src/libs/Navigation/helpers/getReportURLForCurrentContext.ts#L8-L25
The native bundle defers every import to its first use site (Metro-style inline requires, see config/repack/cjs-inline-requires-loader.mjs). So on a cold start that lands directly on the held expense's thread (the app restores the last visited path on reopen), this module is initialized during the first render of the MOVED_TRANSACTION action, and getReportURLForCurrentContext is then called synchronously in that same tick — before the getEnvironmentURL().then(...) callback has had any chance to run. environmentURL is still undefined, so the message HTML is built with the href undefined/r/<reportID> — exactly the string visible in the issue's video.
AnchorRenderer then classifies every rendered anchor's href at render time:
https://github.com/Expensify/App/blob/a66a788c1843dfefa4338d2499dfcb3b008d48dc/src/components/HTMLEngineProvider/HTMLRenderers/AnchorRenderer.tsx#L49-L50
Both helpers parse the href with the URL constructor — getPathFromURL and hasSameExpensifyOrigin — and parsing undefined/r/… throws TypeError: Invalid URL, which their catch blocks log as "Error parsing URL:" / "Error parsing URLs:" (both appear among the 6 logged errors in the video):
https://github.com/Expensify/App/blob/a66a788c1843dfefa4338d2499dfcb3b008d48dc/src/libs/Url.ts#L18-L27
This also explains why QA could not reproduce it reliably: if anything else in the process happens to call getReportURLForCurrentContext in an earlier tick (for example the LHN's last-message text for the same action, which goes through ReportAlternateTextUtils), the module is already initialized and the promise has already resolved by the time the thread renders, so no error is logged. The error is only visible in dev because console.error surfaces there, but the malformed undefined/r/… href is produced in release builds too — tapping that link while it is in this state navigates nowhere useful.
What changes do you think we should make in order to solve the problem?
In getReportURLForCurrentContext, stop interpolating the possibly-unset environmentURL directly. Fall back to the production NewDot origin (CONST.NEW_EXPENSIFY_URL) whenever the asynchronously resolved environmentURL is not available yet, in all three places the function builds a URL (the missing-reportID early return, the plain report URL, and the search-context URL).
This always produces a valid, parseable absolute URL, so the URL parsing in AnchorRenderer's helpers never throws and the console errors disappear. The production origin is also this codebase's canonical "environment not known yet" value — the environment context uses exactly that default while the environment is being resolved:
https://github.com/Expensify/App/blob/a66a788c1843dfefa4338d2499dfcb3b008d48dc/src/components/EnvironmentContextProvider/default.ts#L5-L8
And since the production origin is one of the recognized NewDot origins, the link is still classified as an internal App link, matching how backend-generated report-action HTML (which always carries the production origin) is already handled. Once the environment promise resolves — a few microtasks after the module loads — subsequent renders produce the environment-specific URL exactly as before, so there is no behavior change outside the first-tick window that currently produces the broken undefined/… href.
Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/107179-report-url-env-fallback?expand=1
What alternative solutions did you explore? (Optional)
Threading the environment URL from the useEnvironment() context into getMovedTransactionMessage and getReportURLForCurrentContext as a parameter, so the component re-renders with the resolved URL. This works, but the function is also called from non-React code (context-menu copy actions, report-name derivation), so the parameter would have to be threaded through many call sites to achieve the same net effect as the local fallback.
Suppressing the error at the parsing side (treating invalid hrefs as non-internal links without logging) was discarded: it hides the symptom, but the message would still carry a broken undefined/r/… href that misnavigates when tapped. Fixing the URL construction site is strictly better.
Proposal
Please re-state the problem that we are trying to solve in this issue.
After partially approving a report, reopening the app on iOS logs Error parsing URL: TypeError: Invalid URL in the console.
What is the root cause of that problem?
The bad string is an anchor href built from a module-level environmentURL that is filled asynchronously, so anything that renders before the promise settles interpolates undefined:
https://github.com/Expensify/App/blob/602e80575dda927d9f9ef258e7578a039af4bab8/src/libs/Navigation/helpers/getReportURLForCurrentContext.ts#L8-L9
https://github.com/Expensify/App/blob/602e80575dda927d9f9ef258e7578a039af4bab8/src/libs/Navigation/helpers/getReportURLForCurrentContext.ts#L19-L25
getEnvironmentURL() goes through getEnvironment(). On web and on dev/adhoc native builds it settles in a microtask, long before the first render. On an App Store or TestFlight iOS build it waits on a native module round trip, which can outlast the first render:
https://github.com/Expensify/App/blob/602e80575dda927d9f9ef258e7578a039af4bab8/src/libs/Environment/getEnvironment/index.native.ts#L34-L46
https://github.com/Expensify/App/blob/602e80575dda927d9f9ef258e7578a039af4bab8/src/libs/Environment/betaChecker/index.ios.ts#L8-L13
The partial approval creates a CREATED_REPORT_FOR_UNAPPROVED_TRANSACTIONS action, whose message is built with that helper and handed straight to RenderHTML:
https://github.com/Expensify/App/blob/602e80575dda927d9f9ef258e7578a039af4bab8/src/libs/ReportActionsUtils.ts#L5941-L5947
https://github.com/Expensify/App/blob/602e80575dda927d9f9ef258e7578a039af4bab8/src/components/ReportActionItem/CreatedReportForUnapprovedTransactionsAction.tsx#L21-L32
So the href reads undefined/r/<reportID>, and AnchorRenderer resolves it during render — no tap involved, which is why the stack in the video is TNodeRenderer → renderChildren:
https://github.com/Expensify/App/blob/602e80575dda927d9f9ef258e7578a039af4bab8/src/components/HTMLEngineProvider/HTMLRenderers/AnchorRenderer.tsx#L47-L50
https://github.com/Expensify/App/blob/602e80575dda927d9f9ef258e7578a039af4bab8/src/libs/actions/Link.ts#L139-L148
Both new URL() calls reached from there throw on a scheme-less string, and each logs one line:
https://github.com/Expensify/App/blob/602e80575dda927d9f9ef258e7578a039af4bab8/src/libs/Url.ts#L18-L27
https://github.com/Expensify/App/blob/602e80575dda927d9f9ef258e7578a039af4bab8/src/libs/Url.ts#L32-L43
getInternalNewExpensifyPath therefore returns '', so AnchorRenderer line 67 leaves the anchor without its in-app press handler: the link in the message is also dead, and stays dead, because a module-level variable does not re-render anything once it is filled. A cold reopen matters because module evaluation starts over, putting environmentURL back to undefined while the restored report renders.
// Stands in for the pending native beta check
jest.mock('@libs/Environment/Environment', () => ({...jest.requireActual('@libs/Environment/Environment'), getEnvironmentURL: () => new Promise(() => {})}));
const href = getReportURLForCurrentContext('4945629927818497'); // 'undefined/r/4945629927818497'
getInternalNewExpensifyPath(href); // ''
// console.error Error parsing URL: TypeError: Invalid URL: undefined/r/4945629927818497
// at getPathFromURL (src/libs/Url.ts:24:17)
// console.error Error parsing URLs: TypeError: Invalid URL: undefined/r/4945629927818497
// at hasSameExpensifyOrigin (src/libs/Url.ts:41:17)
Three sibling modules fill environmentURL the same way and interpolate it into hrefs the same way: ReportUtils.ts:1084 (:8701), ReportActionsUtils.ts:176 (:3172, :6054) and ModifiedExpenseMessage.ts:29 (:413).
What changes do you think we should make in order to solve the problem?
Give the variable a usable value for the window before the promise settles, instead of undefined. EnvironmentProvider already does exactly this for its context, with the production URL as the default:
https://github.com/Expensify/App/blob/602e80575dda927d9f9ef258e7578a039af4bab8/src/components/EnvironmentContextProvider/default.ts#L5-L8
Export that same value from src/libs/Environment/Environment.ts, next to ENVIRONMENT_URLS:
/** The environment URL to use until `getEnvironmentURL()` settles. */
const DEFAULT_ENVIRONMENT_URL = ENVIRONMENT_URLS[CONST.ENVIRONMENT.PRODUCTION];
and seed all four modules with it:
-let environmentURL: string;
+let environmentURL = DEFAULT_ENVIRONMENT_URL;
getEnvironmentURL().then((url: string) => (environmentURL = url));
With that, the same scratch case gives href === 'https://new.expensify.com//r/4945629927818497' and getInternalNewExpensifyPath(href) === '/r/4945629927818497', with no console.error. (The doubled slash comes from CONST.NEW_EXPENSIFY_URL ending in / and is what the helper already produces on production today.)
On a production build the default is identical to what getEnvironmentURL() resolves to, so nothing changes once it settles. On staging and QA the early href carries the production origin for that window, which is still one of NEW_EXPENSIFY_ORIGINS in Link.ts:137, so getInternalNewExpensifyPath returns an internal path and the link still opens in-app rather than logging; dev settles before any render.
npx tsc --noEmit is clean with the change, and tests/unit/LinkTest.ts, tests/unit/ModifiedExpenseMessageTest.ts, tests/unit/EnvironmentContextTest.tsx and tests/unit/ReportActionsUtilsTest.ts pass (861 cases).
For regression cover, add a case to tests/unit/ReportActionsUtilsTest.ts that pins getEnvironmentURL to a never-settling promise and asserts getCreatedReportForUnapprovedTransactionsMessage yields an href whose origin getInternalNewExpensifyPath accepts, so a future undefined href fails the suite instead of only the console.
Test branch: https://github.com/Expensify/App/compare/main...trasnake87:App:fix/107179
Regression test
tests/unit/ReportActionsUtilsTest.ts, run with npx jest tests/unit/ReportActionsUtilsTest.ts:
- without the change:
Tests: 1 failed, 680 passed, 681 total - with the change:
Tests: 681 passed, 681 total
Proposal
Please re-state the problem that we are trying to solve in this issue.
On iOS, after splitting an expense, holding one split, approving only the unheld split (which moves the held split into a newly created "held expenses" report), then opening that held expense and reopening the app, the Console logs Error parsing URL: TypeError: Invalid URL. The error is harmless-looking but indicates a malformed link is being rendered inside the held expense report, and it is timing-sensitive (reported as "Unable to reproduce" in staging), which points at a cold-start race rather than a deterministic logic bug.
What is the root cause of that problem?
The held expense moved out of the approved report lives in a new report whose header action is CREATED_REPORT_FOR_UNAPPROVED_TRANSACTIONS. That action is rendered by CreatedReportForUnapprovedTransactionsAction, which builds an anchor to the original report:
The message HTML embeds <a href="${reportUrl}">…</a>, where reportUrl comes from getCreatedReportForUnapprovedTransactionsMessage → getReportURLForCurrentContext.
https://github.com/Expensify/App/blob/7e4a27ab9f34187ac99bcde89a502786c7393896/src/components/ReportActionItem/CreatedReportForUnapprovedTransactionsAction.tsx#L22-L26
getReportURLForCurrentContext prefixes the route with a module-level environmentURL that is populated asynchronously and starts out undefined:
https://github.com/Expensify/App/blob/7e4a27ab9f34187ac99bcde89a502786c7393896/src/libs/Navigation/helpers/getReportURLForCurrentContext.ts#L8-L25
On iOS production/staging builds, getEnvironmentURL() must await betaChecker.isBetaBuild(), so there is a real window on cold start where the promise has not resolved:
https://github.com/Expensify/App/blob/7e4a27ab9f34187ac99bcde89a502786c7393896/src/libs/Environment/getEnvironment/index.native.ts#L14-L47
When the app is killed and reopened directly onto this restored report, the action renders before that promise settles, so environmentURL is undefined and the href becomes the non-absolute string undefined/r/<id>.
Every anchor is then eagerly parsed on render — AnchorRenderer calls getInternalNewExpensifyPath(attrHref) for all hrefs, before any origin check:
https://github.com/Expensify/App/blob/7e4a27ab9f34187ac99bcde89a502786c7393896/src/components/HTMLEngineProvider/HTMLRenderers/AnchorRenderer.tsx#L47-L50
getInternalNewExpensifyPath calls Url.getPathFromURL(href) first (line 144), so the origin guard never gets a chance to short-circuit a relative href:
https://github.com/Expensify/App/blob/7e4a27ab9f34187ac99bcde89a502786c7393896/src/libs/actions/Link.ts#L139-L150
getPathFromURL runs new URL('undefined/r/<id>'), which throws because the string has no scheme, and logs the reported error:
https://github.com/Expensify/App/blob/7e4a27ab9f34187ac99bcde89a502786c7393896/src/libs/Url.ts#L18-L27
So the root cause is not URL parsing or the renderer — it is that getReportURLForCurrentContext emits an undefined origin during the cold-start window before the async environment resolves. This is why it only reproduces on iOS native (the isBetaBuild() async hop) and only when a report carrying this action is restored at launch.
What changes do you think we should make in order to solve the problem?
Give the module-level environmentURL a synchronous default so it is never undefined, exactly as EnvironmentProvider already does for the React context (environmentURL: CONST.NEW_EXPENSIFY_URL):
https://github.com/Expensify/App/blob/7e4a27ab9f34187ac99bcde89a502786c7393896/src/components/EnvironmentContextProvider/default.ts#L5-L8
This is the right default because production is precisely what getEnvironmentURL() resolves to for prod builds, and backend-generated report HTML already bakes in the production origin and relies on the client to rewrite it per environment (rewriteProductionNewDotLinks). During the pre-resolution window the href becomes https://new.expensify.com/r/<id> — a valid absolute URL whose origin matches NEW_EXPENSIFY_ORIGINS, so getInternalNewExpensifyPath still returns the correct internal path and the link stays functional; once the promise settles, staging/dev builds use their own origin on the next render.
In src/libs/Navigation/helpers/getReportURLForCurrentContext.ts, add the CONST import and seed the default:
import CONST from '@src/CONST';
let environmentURL: string = CONST.NEW_EXPENSIFY_URL;
getEnvironmentURL().then((url: string) => (environmentURL = url));
https://github.com/Expensify/App/blob/7e4a27ab9f34187ac99bcde89a502786c7393896/src/libs/Navigation/helpers/getReportURLForCurrentContext.ts#L8-L9
Apply the identical one-line default to the twin declaration in ReportActionsUtils.ts, which carries the same latent race for every other cold-start-rendered action message that interpolates ${environmentURL}/… (CONST is already imported there):
let environmentURL: string = CONST.NEW_EXPENSIFY_URL;
getEnvironmentURL().then((url: string) => (environmentURL = url));
https://github.com/Expensify/App/blob/7e4a27ab9f34187ac99bcde89a502786c7393896/src/libs/ReportActionsUtils.ts#L176-L177
Edge cases and platform notes:
- Cold start / race (the actual trigger): the default removes the only
undefinedwindow; the async assignment still upgrades the value for non-production environments. - Search context branch:
getReportURLForCurrentContextalso returns${environmentURL}/${SEARCH_MONEY_REQUEST_REPORT…}; the default keeps that absolute too, so the same error cannot fire from the search-context path. - Deleted original report:
createdReportForUnapprovedTransactionsrenders plain text with no anchor whenisReportDeletedis true, so that branch is unaffected. - Staging/dev correctness: because production origins are rewritten client-side, defaulting to production does not leave a wrong-environment link visible after resolution.
I intentionally did not change getPathFromURL/AnchorRenderer: suppressing the throw there would hide a genuinely broken (non-navigating) link rather than fix it.
Regression test plan
- Reproduce the issue flow (submit → split → hold one split → approve the unheld split → open the held expense → kill and relaunch directly onto that report) on iOS and confirm no
Error parsing URLappears in the Console. - Tap the linked original-report name in the "created this report for any held expenses from …" message and confirm it navigates to the correct report, both immediately after launch and after the app has fully settled.
- Repeat from a search (Reports) context to exercise the
SEARCH_MONEY_REQUEST_REPORTbranch and verify navigation preserves the search back target. - Verify on a staging/adhoc iOS build that, after the environment resolves, report-action links still point at the staging origin (no stuck-on-production links).
- Unit: add a case asserting
getReportURLForCurrentContext(reportID)returns an absolute URL (never anundefined-prefixed string) when invoked beforegetEnvironmentURL()resolves, and thatgetInternalNewExpensifyPathon that result yields the expected internal path without logging.
I have not run these tests or performed device checks.
Proposal
What is the root cause of that problem?
After the app is reopened on the held expense report, the console logs Error parsing URL: TypeError: Invalid URL. The recording's LogBox shows the bad value, undefined/r/4945629927818497.
CreatedReportForUnapprovedTransactionsAction.tsx builds its message HTML through getCreatedReportForUnapprovedTransactionsMessage, which calls getReportURLForCurrentContext:
https://github.com/Expensify/App/blob/674a843316b5c514d599db4e67e712607f2c995d/src/components/ReportActionItem/CreatedReportForUnapprovedTransactionsAction.tsx
https://github.com/Expensify/App/blob/674a843316b5c514d599db4e67e712607f2c995d/src/libs/Navigation/helpers/getReportURLForCurrentContext.ts
That helper keeps environmentURL in a module-level variable that is only set inside getEnvironmentURL().then(...). On native, the environment resolves asynchronously. If the report action renders before that promise settles, the helper returns undefined/r/{reportID}. AnchorRenderer then classifies this href during render, and Url.ts calls new URL("undefined/r/..."), which throws. The error is caught and logged, so this is a log error, not a crash.
The underlying problem is that the base URL is read from a module variable that has no value yet and cannot trigger a re-render when it gets one.
https://github.com/Expensify/App/blob/674a843316b5c514d599db4e67e712607f2c995d/src/libs/Url.ts
What changes do you think we should make in order to solve the problem?
-
CreatedReportForUnapprovedTransactionsAction.tsx: readenvironmentURLfrom the existinguseEnvironment()hook, which has a synchronous default and re-renders when the real value resolves. Use it when building the message so the link is always valid and updates once the environment is known. -
getReportURLForCurrentContext.ts: accept an optional base URL argument and prefer it over the module variable. Existing callers stay unchanged.
function getReportURLForCurrentContext(reportID: string, baseURL = environmentURL) { ... }
getCreatedReportForUnapprovedTransactionsMessage(the existing message builder): forward the base URL to the helper. This fixes the one path that produces the reported link without changing any other callers.
A plain CONST.NEW_EXPENSIFY_URL default on the module variable would stop the error, but the link would keep the production origin until the next render. In dev or staging, that link could be treated as external, since nothing re-renders it once the real environment resolves. Using the context avoids this.
What alternative solutions did you explore? (Optional)
Wrapping new URL in Url.ts with a base URL would hide the error but would turn undefined/r/... into a valid-looking internal path, so the broken link would remain.
Reminder: Please use plain English, be brief and avoid jargon. Feel free to use images, charts or pseudo-code if necessary. Do not post large multi-line diffs or write walls of text. Do not create PRs unless you have been hired for this job.
🤖 ProposalPolice™ is tracking duplicate proposals for this issue using an OpenAI Conversation. This comment stores that Conversation's ID and can be safely ignored.
Proposal updated — added compare branch with implementation.
Proposal updated: added a test branch.
Proposal
Please re-state the problem that we are trying to solve in this issue.
On iOS, after splitting an expense, holding one split expense, approving only the unheld one, and reopening the app on the held expense, the console shows Error parsing URL: TypeError: Invalid URL. No error should appear: reopening the app on a held expense is an ordinary cold start, and nothing the user did produces an invalid URL.
What is the root cause of that problem?
Report links are built from a module-scoped environmentURL variable that is undefined until an asynchronous lookup resolves, and on native that lookup is genuinely slow at cold start. Any report message rendered before it resolves gets an href starting with the literal string undefined, and parsing that href logs the exact reported error.
The chain, verified file by file:
- Four library files declare the variable uninitialized and fill it in later:
src/libs/Navigation/helpers/getReportURLForCurrentContext.ts:12src/libs/ReportActionsUtils.ts:178(plusoldDotEnvironmentURLat line 181)src/libs/ModifiedExpenseMessage.ts:32src/libs/ReportUtils.ts:1085Each one islet environmentURL: string;followed bygetEnvironmentURL().then((url) => (environmentURL = url));.
- On native,
getEnvironment()insrc/libs/Environment/getEnvironment/index.native.tswaits onbetaChecker.isBetaBuild()(a native bridge call) before it resolves for staging and production builds, so the promise is still pending while the first screens render after a cold start. On web it resolves immediately, which is why this only shows up on iOS. - The repro steps create exactly the message that trips the race. Approving only the unheld split expense creates a
CREATED_REPORT_FOR_UNAPPROVED_TRANSACTIONSsystem action on the held expense report. When that action renders,getCreatedReportForUnapprovedTransactionsMessage(src/libs/ReportActionsUtils.ts:5859) callsgetReportURLForCurrentContext(reportID), which returns`${environmentURL}/r/${reportID}`, i.e."undefined/r/67890"while the lookup is pending. AnchorRendererclassifies that href during rendering (no tap needed) viagetInternalNewExpensifyPath, which callsUrl.getPathFromURL("undefined/r/67890").new URL("undefined/r/67890")throwsTypeError: Invalid URL, andgetPathFromURLcatches it and logsconsole.error('Error parsing URL:', error). That is the exact console error in the issue.
Why the error needs this exact sequence: the partial approval is what creates the system message with the report link, and reopening the app is what makes the message render during the cold-start window before the environment lookup resolves. A warm app has the lookup resolved already, so the same report renders cleanly.
The same uninitialized variable feeds every other link these files build, so the race is not limited to this one message: 14 interpolation sites in ReportActionsUtils.ts (including the %baseURL replacement at line 1948 and the room link at line 3089), 3 sites in ModifiedExpenseMessage.ts, and 13 sites in ReportUtils.ts, plus the oldDot link at ReportActionsUtils.ts:6109. Any of them can emit an undefined origin link if rendered early enough. The components that use useEnvironment() are not affected: EnvironmentContextProvider already defaults its environmentURL to CONST.NEW_EXPENSIFY_URL before the lookup settles, so this fix brings the library files in line with the convention the app already uses.
I confirmed the mechanism with a failing test before fixing: with the environment promise held pending, getReportURLForCurrentContext('67890') returned "undefined/r/67890", and the held-expense system message contained that exact string as its link.
What changes do you think we should make in order to solve the problem?
Initialize each module-scoped URL variable with the production URL as a synchronous default, and keep the asynchronous lookup overwriting it when it resolves. 4 files changed (+18/-5):
src/libs/Navigation/helpers/getReportURLForCurrentContext.ts:let environmentURL: string = CONST.NEW_EXPENSIFY_URL;(adds theCONSTimport).src/libs/ReportActionsUtils.ts: same default forenvironmentURL, andlet oldDotEnvironmentURL: string = CONST.EXPENSIFY_URL;for the oldDot variable.src/libs/ModifiedExpenseMessage.ts:let environmentURL: string = CONST.NEW_EXPENSIFY_URL;.src/libs/ReportUtils.ts:let environmentURL: string = CONST.NEW_EXPENSIFY_URL;.
The async .then assignment in each file is unchanged, so staging, QA, and dev builds still get their real environment URL as soon as the lookup resolves; the default only covers renders that happen before that moment. A render in that window links to the production origin instead of undefined, and navigation still works because only the path matters for internal links. This also matches the existing default in src/components/EnvironmentContextProvider/default.ts.
Tests. New tests/unit/EnvironmentURLRaceTest.ts, 4 tests, all passing with the fix and all 4 failing on baseline (the baseline run returned the literal "undefined/r/67890"):
- Report URL is valid while the environment lookup is still pending.
- The held-expense system message contains a valid report URL while the lookup is still pending.
- The oldDot integration link is valid while the lookup is still pending.
- Once the lookup resolves to the staging URL, later URLs use the staging URL (guards the async overwrite).
The test holds the environment promises pending with a mocked @libs/Environment/Environment module and fresh require calls, which is what makes the cold-start race reproducible in jest: the existing suite cannot see it because the real lookup resolves during module import, before any test runs.
Related suites still green: ReportActionsUtilsTest (575 tests), ModifiedExpenseMessageTest + UrlTest (145 tests), ReportUtilsTest (1697 tests).
What I could not verify. The logs link in the issue points at a private Stack Overflow for Teams thread, so the reporter's failing URL and stack were not available to read; the failing test reproduces the exact console message with the URL identified as "undefined/r/<reportID>". No real-device run of the Applause steps was possible here; manual QA worth doing before merge is: on an iOS staging build, follow the issue steps (split, hold one expense, approve only the other, force-quit and reopen on the held expense) and confirm no console error appears. Lint and full typecheck could not run to green on the prep VM: direct oxlint fails on the known environment breakage (the typescript-estree loader cannot load through the symlinked node_modules) and the full typecheck was not attempted because this machine has repeatedly OOM-killed it. The targeted checks that could run are clean: cspell reports 0 issues on all five changed files and esbuild parses all five. Lint and typecheck should be re-run on a machine with enough memory before the PR is opened.
What alternative solutions did you explore? (Optional)
- Fix only
getReportURLForCurrentContext. Rejected: the same uninitialized variable is interpolated inReportActionsUtils.ts,ModifiedExpenseMessage.ts, andReportUtils.ts, so fixing one file leaves the same broken link in the other message builders. - Make
getReportURLForCurrentContextasynchronous. Rejected: it is called synchronously from message builders during render, so an async version would force async plumbing through every caller and add render flicker, for no benefit over a default that already exists in the app's own context provider. - Give
getPathFromURLa base URL so relative or malformed hrefs parse instead of throwing. Rejected: with a base,"undefined/r/67890"would parse as the internal path"undefined/r/67890"and a tap would navigate to a bogus route instead of doing nothing, turning a loud console error into a silent broken link. It also would not silence the second log, sincehasSameExpensifyOriginparses the href separately. The malformed href should never be generated in the first place. - Silence the
console.erroringetPathFromURL. Rejected: that hides the symptom while every early-rendered link stays broken. - Wait for the failing URL and stack MelvinBot asked for. The failing test identifies the URL (
"undefined/r/<reportID>") and the exact throw site (new URLingetPathFromURL), so the two candidate paths MelvinBot listed are settled in favor of the rendered report link, not the launch URL. - An earlier proposal in this issue suggests the same default initialization for three files. This proposal agrees with that core idea and extends it: it also covers the fourth file with the same pattern (
ReportUtils.ts), covers theoldDotEnvironmentURLvariable, and proves the fix with a failing test that reproduces the exact console error. It does not adopt that proposal'sUrl.tschange, for the reason above.
Contributor details
Your Expensify account email: [email protected]
Upwork Profile Link: https://www.upwork.com/freelancers/~013b564a690d9bcdab