Search code examples
react-nativeimageoauth-2.0expo

React Native Image with Headers failing to load in Android


While trying to access protected images I came across the implementation from React Native's side of using source property with headers. But this approach has a problem with Android devices. It loads perfectly on iOS but when going to Android devices I believe the headers with the token are not being sent properly

At first I thought that the token was not being passed properly, but as you can see in the following code it is properly being sent

import React, { useEffect, useState } from "react";
import { Image, ImageBackground } from "react-native";

import { getAuth } from "../services/auth/auth.js";

const ImageWithToken = ({ imageType, uri, defaultImage, ...rest }) => {
  const [newUri, setNewUri] = useState(null);

  useEffect(() => {
    const getToken = async () => {
      const tok = await getAuth();
      if (!tok) getToken();
      setNewUri({
        uri: uri,
        headers: { Authorization: "Bearer " + tok?.access_token },
      });
    };

    getToken();

    return () => {
      console.log("Cleanup");
    };
  }, []);

  if (!newUri) {
    console.log("There is no token");
    return <></>;
  }

  return (
    <>
      {console.log("im here")}
      {imageType === "imageBackground" ? (
         <ImageBackground
           source={uri ? newUri : defaultImage}
           {...rest}
         ></ImageBackground>
      ) : (
        <Image source={uri ? newUri : defaultImage} {...rest}></Image>
      )}
    </>
  );
};

export default ImageWithToken;

The method getAuth provides with the logged in token of the application. I came across several posts informing of React Native failures with Image Headers as in here and I wanted to confirm that the problems where coming from it rather than from my code, and if there are other alternatives as I have to load an Image carousel. To clarify the project is being built with Expo Thanks in advance


Solution

  • After several checks and updates thanks to Dustin I realized there was a possibility to use expo-image upgrading the project to Expo SDK 48 (Checkout this post), even though it was not specified the library was available since that version without using development builds(necessary for our project). Aside from this, the manual upgrade of the library was needed to the latest version as it provided ImageBackground properties, as the ones found in React Native's library by default but with the proper implementation for Headers. Due to this a warning was triggered as Expo was expecting a different library version for expo-image. This allowed us to build without errors, just the warning mentioned before. So for anyone having the same problem I hope this will be helpful