Skip to content

[$175] [Sentry: APP-NZR] TypeError: Cannot read properties of undefined (reading 'toLowerCase') #106409

Open

Description

@MelvinBot

Summary

Editing the receipt requirement amount can throw an unhandled TypeError when a keyboard event has no nativeEvent.key.

Sentry: https://expensify.sentry.io/issues/APP-NZR

Reported impact: 1 user, 2 events; first seen November 8, 2026 at 19:36 UTC.

Platform: Web, Chrome Mobile on Android, standalone.
Release: 9.5.33
Route: /workspaces/:policyID/rules/require-receipts
Mechanism: Unhandled (onerror), level error.

Error and first-party frames

TypeError: Cannot read properties of undefined (reading 'toLowerCase')

src/components/AmountEditingController/utils.ts:26 — isForwardDeleteKeyPress
  const key = event.nativeEvent.key.toLowerCase();
src/components/AmountEditingController/hooks/useAmountSelection.ts:75
  forwardDeletePressedRef.current = isForwardDeleteKeyPress(event);
AmountFormFieldInput.tsx:39 — handleInputKeyPress
  handleKeyPress(event);
react-native-web TextInput handleKeyDown → onKeyPress(e)

Root cause

AmountEditingController/utils.ts:25–39 calls event.nativeEvent.key.toLowerCase() without checking that key is a string. The amount input forwards keyboard events into this helper, so an undefined key throws instead of being treated as a non-forward-delete event.

Mobile Chrome/IME behavior is a suspected trigger, not confirmed. Exact UI reproduction steps have not been established.

Expected behavior

Receipt-threshold editing should not throw when a keyboard event has a missing or non-string key.

Suggested fix

  • Return false for missing/non-string keys before calling toLowerCase().
  • Add regression coverage for missing/non-string keys and existing forward-delete shortcuts.

Parent tracker: [Tracking] Top Sentry crashes monthly check-in

Slack thread: https://expensify.slack.com/archives/C027V2LD9D1/p1794236798557059

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @Julesssss

Activity

  1. added
    ExternalAdded to denote the issue can be worked on by a contributor
    BugSomething is broken. Auto assigns a BugZero manager.
    on Nov 9, 2026
  2. melvin-bot commented on Nov 9, 2026

    @melvin-bot

    Triggered auto assignment to Contributor-plus team member for initial proposal review - @parasharrajat (External)

  3. changed the title [-][Sentry: APP-NZR] TypeError: Cannot read properties of undefined (reading 'toLowerCase')[/-] [+][$175] [Sentry: APP-NZR] TypeError: Cannot read properties of undefined (reading 'toLowerCase')[/+] on Nov 9, 2026
  4. melvin-bot commented on Nov 9, 2026

    @melvin-bot
  5. self-assigned this
    on Nov 9, 2026
  6. moved this from CRITICAL to SUBISSUE in [#whatsnext] #qualityon Nov 9, 2026
  7. fitzyracing1 commented on Nov 9, 2026

    @fitzyracing1

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    Typing in the receipt requirement amount field (/workspaces/:policyID/rules/require-receipts) can crash with TypeError: Cannot read properties of undefined (reading 'toLowerCase') when the keyboard event reaching the amount editor has no nativeEvent.key, which Sentry shows on Chrome for Android.

    What is the root cause of that problem?

    Some keyboard events on Android Chrome (likely IME or autofill, as the issue notes) arrive without a key. react-native-web's TextInput passes those events on to onKeyPress unchanged. The amount editor then assumes key is always a string:

    • isForwardDeleteKeyPress in src/components/AmountEditingController/utils.ts calls event.nativeEvent.key.toLowerCase() with no check (line 26). It's called from handleKeyPress in hooks/useAmountSelection.ts, which is the stack in Sentry.
    • handleKeyPress in src/components/AmountEditingController/hooks/useDetachedSignEditingController.ts (line 78) does the same event.nativeEvent.key.toLowerCase() before delegating to the controller. Any input that uses the detached sign controller would hit the same crash one frame earlier.

    AmountEditingKeyPressEvent in types.ts types key as a plain string, so TypeScript doesn't flag either call.

    What changes do you think we should make in order to solve the problem?

    1. In utils.ts, add a small helper, e.g. getNormalizedKey(event), that returns event.nativeEvent?.key lowercased when it's a string and '' otherwise. Use it in isForwardDeleteKeyPress, so a missing key simply returns false (not a forward delete).
    2. Use the same helper in useDetachedSignEditingController.ts's handleKeyPress, so the backspace check is skipped and the event still goes on to controller.handleKeyPress.
    3. Change key in AmountEditingKeyPressEvent to key?: string so the types match what the browser actually sends and future callers have to handle it.

    Forward-delete (Delete, Ctrl+D on macOS/iOS, the iOS Safari accessibility Ctrl case) and backspace sign deletion keep working as before.

    What specific scenarios should we cover in automated tests?

    In tests/unit/components/AmountEditingControllerUtilsTest.ts:

    • isForwardDeleteKeyPress returns false and doesn't throw when nativeEvent.key is undefined, a non-string, or 'Unidentified'.
    • The existing Delete and macOS Ctrl+D cases still return true.

    In tests/unit/components/useDetachedSignEditingControllerTest.tsx:

    • handleKeyPress with a missing key doesn't throw, doesn't delete the sign, and still forwards the event to the base controller.

    What alternative solutions did you explore? (Optional)

    Using optional chaining at each call site (event.nativeEvent.key?.toLowerCase()). That fixes the crash too, but one shared helper plus the optional type is safer, because both call sites behave the same and the compiler catches new ones.

  8. kevinjosh10 commented on Nov 9, 2026

    @kevinjosh10

    Proposal

    What is the root cause of that problem?

    There are two affected call sites in the amount editing controller pipeline where event.nativeEvent.key.toLowerCase() is called without verifying that key is a valid string:

    1. Forward-delete keypress detector (src/components/AmountEditingController/utils.ts:25-27)

    function isForwardDeleteKeyPress(event: AmountEditingKeyPressEvent): boolean {
        const key = event.nativeEvent.key.toLowerCase();

    In React Native Web's TextInput keyboard pipeline, Android Chrome virtual keyboards, composition/IME events, and autofill often emit synthetic key events where nativeEvent.key is undefined (or empty/non-string). Calling .toLowerCase() directly on undefined throws TypeError: Cannot read properties of undefined (reading 'toLowerCase').

    2. Detached-sign controller handler (src/components/AmountEditingController/hooks/useDetachedSignEditingController.ts:77-85)

    const handleKeyPress = (event: AmountEditingKeyPressEvent) => {
        const key = event.nativeEvent.key.toLowerCase();
    
        if (key === 'backspace') {
            deleteSignBeforeCaret();
        }
    
        controller.handleKeyPress(event);
    };

    useDetachedSignEditingController performs the exact same unsafe .toLowerCase() operation. Any amount screen utilizing detached signs (such as negative expenses or detached currency sign controllers) crashes with the identical unhandled TypeError when an IME or autofill key event arrives.

    3. Strict typing masks optionality (src/components/AmountEditingController/types.ts:7-12)

    type AmountEditingKeyPressEvent = {
        nativeEvent: {
            key: string;
            ctrlKey?: boolean;
        };
    };

    Because key is typed as a required string, TypeScript does not warn developers that browser/native synthetic events can dispatch with key omitted or undefined.


    What changes do you think we should make in order to solve the problem?

    1. Guard rawKey in isForwardDeleteKeyPress (src/components/AmountEditingController/utils.ts:25-37)

    Safely check that rawKey is a string before calling .toLowerCase(). If missing or non-string, return false early:

    function isForwardDeleteKeyPress(event: AmountEditingKeyPressEvent): boolean {
        const rawKey = event.nativeEvent.key;
        if (typeof rawKey !== 'string') {
            return false;
        }
    
        const key = rawKey.toLowerCase();
        if (isMobileSafari() && key === CONST.PLATFORM_SPECIFIC_KEYS.CTRL.DEFAULT) {
            // ...
        }
    }

    2. Guard useDetachedSignEditingController with unconditional delegation (src/components/AmountEditingController/hooks/useDetachedSignEditingController.ts:77-85)

    const handleKeyPress = (event: AmountEditingKeyPressEvent) => {
        const key = event.nativeEvent.key;
    
        if (typeof key === 'string' && key.toLowerCase() === 'backspace') {
            deleteSignBeforeCaret();
        }
    
        controller.handleKeyPress(event);
    };

    Critical Architectural Invariant: controller.handleKeyPress(event) must always be called unconditionally, even when key is missing or malformed. In useAmountSelection.ts:74-76, handleKeyPress updates forwardDeletePressedRef.current = isForwardDeleteKeyPress(event). If a malformed key event were dropped without delegating, any previous forward-delete flag would remain stale and incorrectly offset the caret on subsequent edits! Unconditional delegation resets the flag safely.

    3. Update type definition in types.ts (src/components/AmountEditingController/types.ts:7-12)

    type AmountEditingKeyPressEvent = {
        nativeEvent: {
            key?: string;
            ctrlKey?: boolean;
        };
    };

    What alternative solutions did you explore? (Optional)

    • Only guarding isForwardDeleteKeyPress (competitor approach): Leaves useDetachedSignEditingController completely exposed to the exact same production crash.
    • Optional chaining without type check (event?.nativeEvent?.key?.toLowerCase()): While safe against undefined, it still throws if key is passed as a non-string object/number from unexpected native bridge event structures. Using typeof rawKey !== 'string' is standard in Expensify core libraries.

    What automated tests can you add to prevent this from re-occurring?

    1. In tests/unit/components/AmountEditingControllerUtilsTest.ts:
      Add tests under describe('isForwardDeleteKeyPress'):

      it('returns false without throwing when key is undefined, null, or missing', () => {
          expect(isForwardDeleteKeyPress({nativeEvent: {}} as AmountEditingKeyPressEvent)).toBe(false);
          expect(isForwardDeleteKeyPress({nativeEvent: {key: undefined}} as unknown as AmountEditingKeyPressEvent)).toBe(false);
          expect(isForwardDeleteKeyPress({nativeEvent: {key: null}} as unknown as AmountEditingKeyPressEvent)).toBe(false);
      });
    2. In tests/unit/components/useDetachedSignEditingControllerTest.tsx:
      Add a test verifying that handleKeyPress gracefully handles keyless events and still delegates to the underlying controller without throwing:

      it('handles malformed keypress events without throwing and clears forward-delete state', () => {
          const {result} = renderController({value: '10'});
          expect(() => {
              act(() => result.current.handleKeyPress({nativeEvent: {}} as AmountEditingKeyPressEvent));
          }).not.toThrow();
      });

    Contributor details

    Your Expensify account email: lkevinjosh10@gmail.com
    Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374

  9. melvin-bot commented on Nov 9, 2026

    @melvin-bot

    ✅ Contributor details stored successfully. Thank you for contributing to Expensify!

  10. 10 remaining items

  11. parasharrajat commented on Nov 11, 2026

    @parasharrajat
    Member

    @MelvinBot Propose solution here.

  12. MelvinBot commented on Nov 11, 2026

    @MelvinBot
    ContributorAuthor

    Proposal

    What is the root cause of that problem?

    The amount editor calls event.nativeEvent.key.toLowerCase() without checking whether key is a string. A missing key therefore produces the exact reported exception.

    There are two affected handlers: the forward-delete helper in the reported stack and the detached-sign controller, which performs the same unsafe operation before forwarding the event.

    Code evidence

    This explains the supplied Sentry stack; option-search filtering does not. The exact keyboard/IME trigger remains unconfirmed.

    What changes do you think we should make in order to solve the problem?

    1. Guard both handlers with a string-type check. The forward-delete helper should return false for missing/non-string keys.
    2. In the detached-sign handler, only perform backspace sign deletion for a valid string key. Always forward the event to the base controller, including malformed keys, so its previous forward-delete state is cleared.
    3. Make key optional in the local event type. Retain runtime type guards to handle unexpected non-string values.
    4. Add regression tests covering:
      • Missing, undefined, null, and non-string keys without exceptions.
      • No accidental sign deletion.
      • Forward-delete state resetting after a malformed event.
      • Existing Delete, macOS/iOS Ctrl+D, Safari accessibility Control, and Backspace behavior.

    The existing three relevant unit suites passed: 84 tests. No code was changed, and the production keyboard sequence was not reproduced.

    What alternative solutions did you explore? (Optional)

    Optional chaining alone handles missing keys but still throws for non-string values. Guarding only the forward-delete helper leaves the detached-sign handler vulnerable. Unrelated option-filter changes would not address this stack.


    Next Steps for Contributor+ team:
    To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/106409) to create a draft PR.
    To refine: @MelvinBot <your feedback>
    To reject: Explain why you are rejecting Melvin's proposal.


    view run

  13. gorky117-cell commented on Nov 11, 2026

    @gorky117-cell

    Hi @parasharrajat, my proposal from Nov 9 already covers this exact solution—guarding both isForwardDeleteKeyPress and useDetachedSignEditingController, updating the AmountEditingKeyPressEvent type, and adding regression tests for missing/undefined keys.

    I have the branch and unit test suite tested and ready to open as a PR immediately if assigned. Thank you!

  14. parasharrajat commented on Nov 11, 2026

    @parasharrajat
    Member

    @gorky117-cell we don't accept proposals like that. Please read contributing guidelines

  15. parasharrajat commented on Nov 11, 2026

    @parasharrajat
    Member

    @MelvinBot What is your suggested code change for your proposal here #106409 (comment)

  16. MelvinBot commented on Nov 11, 2026

    @MelvinBot
    ContributorAuthor

    I suggest these three changes, without introducing a shared helper:

    1. In utils.ts:25–37, replace the initial normalization with:

    const rawKey = event.nativeEvent.key;
    if (typeof rawKey !== 'string') {
        return false;
    }
    
    const key = rawKey.toLowerCase();

    Keep the remaining forward-delete shortcut logic unchanged.

    2. In useDetachedSignEditingController.ts:77–85, replace the handler with:

    const handleKeyPress = (event: AmountEditingKeyPressEvent) => {
        const key = event.nativeEvent.key;
    
        if (typeof key === 'string' && key.toLowerCase() === 'backspace') {
            deleteSignBeforeCaret();
        }
    
        controller.handleKeyPress(event);
    };

    The unconditional delegation matters: malformed keys must still reach the base controller to clear any previous forward-delete flag.

    3. In types.ts:7–12, make the key optional:

    type AmountEditingKeyPressEvent = {
        nativeEvent: {
            key?: string;
            ctrlKey?: boolean;
        };
    };

    The optional type captures missing keys; the runtime typeof checks additionally protect against unexpected non-string values.

    Regression coverage should verify missing/non-string keys, preserved sign and shortcut behavior, and resetting forward-delete state after a malformed event. These are suggested changes only; I haven’t applied them.


    view run

  17. parasharrajat commented on Nov 11, 2026

    @parasharrajat
    Member

    @MelvinBot Implement your proposal #106409 (comment).

    🎀 👀 🎀 C+ reviewed

  18. melvin-bot commented on Nov 11, 2026

    @melvin-bot

    Triggered auto assignment to @Julesssss, see https://stackoverflow.com/c/expensify/questions/7972 for more details.

  19. deleted a comment from MelvinBot on Nov 11, 2026
  20. Julesssss commented on Nov 11, 2026

    @Julesssss
    Contributor

    @parasharrajat please go ahead

  21. removed their assignment
    on Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

BugSomething is broken. Auto assigns a BugZero manager.ExternalAdded to denote the issue can be worked on by a contributorReviewingHas a PR in reviewWeeklyKSv2

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions