# OAuth Providers and Anonymous Auth — Firebase

Source: https://www.skillbyai.com/en/firebase/au-oauth

> Social sign-in and upgrading guests.

## Providers, guests and linking

Federated providers such as Google, Apple, GitHub and Microsoft use provider classes (`GoogleAuthProvider`, `OAuthProvider`...) with `signInWithPopup` or `signInWithRedirect`. **Anonymous auth** (`signInAnonymously`) creates a real user with a uid but no credentials, useful for letting people try the app before signing up. When the guest later chooses a provider, **account linking** (`linkWithPopup`, `linkWithCredential`) attaches that credential to the same uid, so their data stays with them. If the credential already belongs to another account, linking fails with `auth/credential-already-in-use` and you must decide how to merge.

## Google sign-in and upgrading a guest

TypeScript.

```typescript
import {
  getAuth, GoogleAuthProvider, signInWithPopup,
  signInAnonymously, linkWithPopup,
} from "firebase/auth";

const auth = getAuth(app);
const google = new GoogleAuthProvider();

export const signInWithGoogle = () => signInWithPopup(auth, google);

export const startAsGuest = () => signInAnonymously(auth);

export async function upgradeGuestToGoogle() {
  const user = auth.currentUser;
  if (!user?.isAnonymous) return;
  try {
    await linkWithPopup(user, google); // same uid, now with a Google credential
  } catch (e: any) {
    if (e.code === "auth/credential-already-in-use") {
      // the Google account already has a Firebase user: merge data deliberately
    }
    throw e;
  }
}
```

## A visitor badge that becomes an employee badge

Anonymous auth gives a visitor a badge number; linking later prints their name on that same badge instead of issuing a new one.

**Quiz:** Why link an anonymous account instead of signing in fresh with Google?

- [ ] Anonymous accounts cannot be deleted
- [x] The user keeps the same uid, so data written as a guest stays theirs
- [ ] Linking is required to use Firestore
- [ ] Google sign-in does not create a uid

*Answer:* The user keeps the same uid, so data written as a guest stays theirs. Linking adds a credential to the existing user.
