Fix auth.currentUser.photoURL returning 404 in Firebase

A few days ago, I got an error displaying one of the user's profile pictures on one of my websites. Firebase auth.currentUser was returning a profile picture with an invalid URL (404 error).

I took a look at the auth.currentUser object and I found 2 similar properties:

jsx
{
    photoURL: 'picture_1.jpg',
    providerData: [{
        photoURL: 'picture_2.jpg'
    }]
    
}

In normal circumstances, picture_1.jpg is equal to picture_2.jpg. But if the user changes the profile picture in his Google account (or Facebook, or Twitter, or whatever), picture_2.jpg will change but picture_1.jpg may not.

Thus, picture_1.jpg may be broken.😅

Summarizing, we need to check whether the two images are equal or not:

jsx
const checkProfilePic = () => {
    
    let user = auth.currentUser;
    
    let firebasePhotoURL = user.photoURL;
    let providerPhotoURL = user.providerData[0].photoURL;

    if(firebasePhotoURL !== providerPhotoURL){

        updateProfilePic(providerPhotoURL);

    }

}

To update the user's Firebase profile picture:

jsx
const updateProfilePic = async (photoURL) => {
    
    let user = auth.currentUser;
    
    await user.updateProfile({'photoURL': photoURL});
    
    // After this point user's profile pic is updated
    
}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.