Skip to content

Fix web image caching authentication issues with expo-image #83112

Closed

Description

@Julesssss

Summary

Part of our App wider performance project

Web is now using expo-image, so receipt images should be cached and not get unnecessarily re-retrieved. HOWEVER:

expo-image has problems with caching if headers are provided (auth header, for example) too. So it needs to be handled separately.

Secondary issue to verify:

  1. Login to staging.new.expensify.com
  2. Open the chat with expenses with receipts images
  3. Make sure they are loaded
  4. Go back to inbox/any other page
  5. Turn off the internet connection (for real, not simulation)
  6. Return to the chat from step 2.
  7. The receipts images that were loaded previously are displayed.

Original discussion here. I believe expo image is being implemented as part of the FlashList migration task here.

Activity

  1. Julesssss commented on Feb 20, 2026

    @Julesssss
    ContributorAuthor

    Linked to #33725, creating this separately in case other work is required outside of FlatList migration.

  2. VickyStash commented on Mar 3, 2026

    @VickyStash
    Contributor

    The BaseImage was migrated to use expo-image #83325, but it also has problems with caching if headers are provided (basically under the hood it has a really similar approach as our patch for react-native-web had). So we will need to handle it ourselves.

  3. changed the title [-]Improve web image caching with expo-image[/-] [+]Fix web image caching authentication issues with expo-image[/+] on Mar 3, 2026
  4. VickyStash commented on Mar 5, 2026

    @VickyStash
    Contributor

    Update:
    Today I had a spare moment and experimented with Claude a little.
    It looks like the easiest way to go is to use the Cache API to cache auth images on web.
    I've got a super simple hook created

    useCachedImageSource
    import type {ImageSource} from 'expo-image';
    import {useEffect, useState} from 'react';
    
    const CACHE_NAME = 'auth-images';
    
    function useCachedImageSource(source: ImageSource | undefined): ImageSource | null | undefined {
        const uri = typeof source === 'object' ? source?.uri : undefined;
        const hasHeaders = typeof source === 'object' && !!source?.headers;
        const [cachedUri, setCachedUri] = useState<string | null>(null);
    
        useEffect(() => {
            if (!hasHeaders || !uri) {
                return;
            }
    
            let revoked = false;
            let objectURL: string | undefined;
    
            (async () => {
                try {
                    const cache = await caches.open(CACHE_NAME);
                    const cachedResponse = await cache.match(uri);
    
                    if (cachedResponse) {
                        const blob = await cachedResponse.blob();
                        objectURL = URL.createObjectURL(blob);
                        if (!revoked) {
                            setCachedUri(objectURL);
                        } else {
                            URL.revokeObjectURL(objectURL);
                        }
                        return;
                    }
    
                    const response = await fetch(uri, {
                        headers: (source as ImageSource).headers as Record<string, string>,
                    });
    
                    if (!response.ok) {
                        throw new Error(`Failed to fetch image: ${response.status}`);
                    }
    
                    // Store in cache before consuming
                    await cache.put(uri, response.clone());
    
                    const blob = await response.blob();
                    objectURL = URL.createObjectURL(blob);
                    if (!revoked) {
                        setCachedUri(objectURL);
                    } else {
                        URL.revokeObjectURL(objectURL);
                    }
                } catch {
                    // Fall through — cachedUri stays null, expo-image will handle it
                }
            })();
    
            return () => {
                revoked = true;
                if (objectURL) {
                    URL.revokeObjectURL(objectURL);
                }
            };
        }, [uri, hasHeaders, source]);
    
        if (!hasHeaders) {
            return source;
        }
    
        if (!cachedUri) {
            return null;
        }
    
        return {uri: cachedUri};
    }
    
    export default useCachedImageSource;
    

    and then in BaseImage.tsx

        const cachedSource = useCachedImageSource(typeof source === 'object' && !Array.isArray(source) ? source : undefined);
        const resolvedSource = cachedSource !== undefined ? cachedSource : source;
    

    Aaand it seems to work

    Monosnap.screencast.2026-03-05.18-08-49.mp4

    If we go this way I guess there can be some overlap with this PR work #65321, so I need to take a closer look at it

  5. VickyStash commented on Mar 6, 2026

    @VickyStash
    Contributor

    Updates:

    • I've put the hook I've mentioned in the Draft PR, so it's easier to check.

    Draft PR:

    pr.mp4

    Production:

    prod.mp4

    @NJ-2020 Since you are working on #65321, what do you think? Will it overlap with your logic? Do you think it's better to wait for your PR to be merged? Cause I guess these types of updates will also touch the attachments caching, as attachments also require authentication.
    cc @Julesssss


    Note: I'll be OOO March 9-10 🌴 , back on March 11th

  6. NJ-2020 commented on Mar 6, 2026

    @NJ-2020
    Contributor

    FYI: Currently in this PR (1/2) we only implement store/caching logic (libs/actions/Attachment, libs/CacheAPI), & in the next PR (2/2) we'll create a hook used for displaying the local attachment source

    @NJ-2020 Since you are working on #65321, what do you think? Will it overlap with your logic? Do you think it's better to wait for your PR to be merged? Cause I guess these types of updates will also touch the attachments caching, as attachments also require authentication.

    Not reallyyy, but since we already have pre-built logic regarding attachment caching, so maybe it's better to wait,

    We've also done something similar before — caching remote images — though those changes were later reverted to only handle upload file attachments and markdown attachments. Here's the relevant commit / #9402 (comment).

    Curious to hear what others think. Thanks!

    cc: @Julesssss

  7. Julesssss commented on Mar 7, 2026

    @Julesssss
    ContributorAuthor

    The draft POC works very nicely for web.

    Your work has minor overlap IMO, so I think we should go ahead with both. @VickyStash's work is a small change and immidiately enables web caching for remote images. After merging @NJ-2020's cache feature we would just have a redundant 2nd cache (local upload and then the remote image). I think that's totally fine for now and helps us ship large improvements faster. Then we can remove that that in PR 2/2 @NJ-2020?

    They are separate cache's so I don't think it should affect @NJ-2020's PR 🤞 Also the time/place of cache is separate.

  8. NJ-2020 commented on Mar 7, 2026

    @NJ-2020
    Contributor

    Your work has minor overlap IMO, so I think we should go ahead with both. @VickyStash's work is a small change and immidiately enables web caching for remote images

    Yeah, I think I have no issues to go with this PR

    After merging @NJ-2020's cache feature we would just have a redundant 2nd cache (local upload and then the remote image).

    Yes, but I think it doesn't prevent the flash bug (switching from local to remote source)

    I think that's totally fine for now and helps us ship large improvements faster. Then we can remove that that in PR 2/2 @NJ-2020?

    I think we still need a some adjustments after merging my PR

    They are separate cache's so I don't think it should affect @NJ-2020's PR 🤞 Also the time/place of cache is separate.

    👍

  9. Julesssss commented on Mar 9, 2026

    @Julesssss
    ContributorAuthor

    Yes, but I think it doesn't prevent the flash bug
    think we still need a some adjustments after merging my PR

    @NJ-2020 ah right, thanks. But lets continue still

  10. 16 remaining items

  11. VickyStash commented on Apr 3, 2026

    @VickyStash
    Contributor

    Updates:
    I've applied codex review feedback and cleanup, but unfortunately during the testing I still found a flickering issue in the scenario when a transaction is opened for the first time (ios mweb).
    Next week I'll be more focused on the FlashList migration issue, but will do my best to try to finalize the work here as well.
    On Monday, I'll be OOO (Easter Monday).

  12. VickyStash commented on Apr 10, 2026

    @VickyStash
    Contributor

    I plan to return to this one next week!

  13. VickyStash commented on Apr 14, 2026

    @VickyStash
    Contributor

    Updates:

    • Experimenting with the solution. Partially the flickering also happens due to shouldOpacityBeZero flag
      /**
      * If the image fails to load and the object position is top, we should hide the image by setting the opacity to 0.
      */
      const shouldOpacityBeZero = isObjectPositionTop && !aspectRatio;

    In comments it says If the image fails to load, but in fact it also adds opacity until the aspect ratio is calculated.
    So I'm trying to improve it in some way.

  14. VickyStash commented on Apr 15, 2026

    @VickyStash
    Contributor

    Updates:

    • Experimenting with a changed approach - instead of preloading adjacent transactions, I'm trying a general-purpose in-memory blob cache in useCachedImageSource. Simple map (up to 20 entries) that keeps blob URLs alive after the component unmounts, so when the same image mounts again it gets the blob URL instantly without waiting for the Cache API. Images that are still on screen can't be evicted, the rest get cleaned up LRU-style when the map is full.
    • Also caching the aspect ratio alongside the blob - this way on re-mount the image already knows its dimensions, which should fix the shouldOpacityBeZero flash I mentioned yesterday.
    • Overall locally it feels better, but I need to test over all of the platforms and review with Claude/Codex
  15. VickyStash commented on Apr 17, 2026

    @VickyStash
    Contributor

    UPD: I've switched to FlashList migration deploy blockers/follow-ups. I'll return to it when I have a moment!

  16. VickyStash commented on Apr 23, 2026

    @VickyStash
    Contributor

    Hi there, I'm going to be OOO till 6th May 🌴
    If you think it's better to re-assign this issue, please, reach out to @MrMuzyk, he will help to find someone

  17. VickyStash commented on May 6, 2026

    @VickyStash
    Contributor

    I'm back from vacation and returning to this issue!
    Maybe I'll give one more try to maintainVisibleContentPosition.startRenderingFromBottom approach, as besides solving the issue it will give us some perf benefits (as was mentioned by @sosek108, though we ended up having some bugs there).
    If no luck, I'll continue with #83112 (comment).
    Hope to provide more details tomorrow!

  18. VickyStash commented on May 7, 2026

    @VickyStash
    Contributor

    I'll give one more try to maintainVisibleContentPosition.startRenderingFromBottom approach, as besides solving the issue it will give us some perf benefits

    You can check the progress here: #89768 (comment)

  19. VickyStash commented on May 14, 2026

    @VickyStash
    Contributor

    Before:

    before.mov

    With #90218:

    after.mov
  20. Julesssss commented on May 14, 2026

    @Julesssss
    ContributorAuthor

    Nice, will check out the PR

  21. VickyStash commented on May 20, 2026

    @VickyStash
    Contributor

    PR #90218 was deployed to prod!

  22. VickyStash commented on May 25, 2026

    @VickyStash
    Contributor

    @Julesssss, I guess we can close this issue, right?

  23. Julesssss commented on May 26, 2026

    @Julesssss
    ContributorAuthor

    Yeah, thanks for checking

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions