0

Tech: Firebase, Next.js, Google Sign in, Firebase Stripe exstension

Bug reproduction:

  • When login with Google

  • Subscribe on stripe

  • Stripe saves subscription data for that user in firestore

  • Logout

  • Login in with Google and old data are overide with new one, and Subscription is lost

Does anyone had similar problem?

Maybe my implementation of Sign-in is bad, here is the Google Sign in code:

const handleGoogleLogin = () => {
    signInWithPopup(auth, googleProvider)
      .then(async result => {
        if (!result.user) return;

        const { displayName, email, uid, providerData, photoURL, phoneNumber } =
          result.user;

        const name = splitName(displayName as string);
        const providerId =
          (providerData.length && providerData[0]?.providerId) || '';

        const data = {
          firstName: name?.firstName || '',
          lastName: name?.lastName || '',
          email,
          photoURL,
          phoneNumber,
          providerId,
        };
        await updateUser(uid, data);
      })
      .catch(error => {
        console.log('Google login error: ', error);
      });
  };

Update user function:

export const updateUser = async (uid: string, data: UpdateUserParams) => {
  try {
    if (!uid) {
      return;
    }

    await setDoc(doc(firestore, 'users', uid), {
      account: {
        ...data,
        initials: `${data.firstName[0]}${data.lastName[0]}`,
      },
    });
  } catch (error) {
    console.error('Error updating user: ', error);
  }
};
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Mark James
  • 338
  • 4
  • 15
  • 43
  • 1
    It's not clear what you mean by "data are overide with new one, and Subscription is lost". Please edit the question to explain what you are observing, and all relevant code that performs these actions. There should be enough information in the question that anyone can use to reproduce the behavior. – Doug Stevenson Feb 19 '23 at 23:10
  • Updated with all code related. – Mark James Feb 19 '23 at 23:12
  • I mean on stripe add by default some subscription data for the subscribed users, when the user go logout, and login again with Google Sign-in, those stripe data are deleted automaticity. – Mark James Feb 19 '23 at 23:13
  • When user logs in again with google it looks like it's registered from scratch, maybe I should add { merge true } somewhere when logs in – Mark James Feb 19 '23 at 23:14

1 Answers1

1

setDoc is overwriting the contents of the document with each sign-in. You should instead use set with merge to prevent overwriting the fields you don't want to lose, or check first if the document exists before creating it.

See also:

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441