Authenticate with Firebase Anonymously Using JavaScript (original) (raw)

You can use Firebase Authentication to create and use temporary anonymous accounts to authenticate with Firebase. These temporary anonymous accounts can be used to allow users who haven't yet signed up to your app to work with data protected by security rules. If an anonymous user decides to sign up to your app, you canlink their sign-in credentials to the anonymous account so that they can continue to work with their protected data in future sessions.

Before you begin

  1. Add Firebase to your JavaScript project.
  2. If you haven't yet connected your app to your Firebase project, do so from the Firebase console.
  3. Enable anonymous authentication:
    1. In the Firebase console, go toSecurity > Authentication.
    2. In the Sign-in method tab, enable the Anonymous sign-in provider.
    3. Optional: If you've upgraded your project toFirebase Authentication with Identity Platform, you can enable automatic clean-up. When you enable this setting, anonymous accounts older than 30 days will be automatically deleted. In projects with automatic clean-up enabled, anonymous authentication will no longer count toward usage limits or billing quotas. SeeAutomatic clean-up.

When a signed-out user uses an app feature that requires authentication with Firebase, sign in the user anonymously by completing the following steps:

  1. Call the signInAnonymously method:

Web

import { getAuth, signInAnonymously } from "firebase/auth";
const auth = getAuth();
signInAnonymously(auth)
.then(() => {
// Signed in..
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ...
});

Web

firebase.auth().signInAnonymously()
.then(() => {
// Signed in..
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
This is also where you can catch and handle errors. For a list of error codes have a look at the Auth Reference Docs. 2. If the signInAnonymously method completes without error, the observer registered in the onAuthStateChanged will trigger and you can get the anonymous user's account data from the User object:

Web

import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/auth.user
const uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});

Web

firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/v8/firebase.User
var uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});

Convert an anonymous account to a permanent account

When an anonymous user signs up to your app, you might want to allow them to continue their work with their new account—for example, you might want to make the items the user added to their shopping cart before they signed up available in their new account's shopping cart. To do so, complete the following steps:

  1. When the user signs up, complete the sign-in flow for the user's authentication provider up to, but not including, calling one of theAuth.signInWith methods. For example, get the user's Google ID token, Facebook access token, or email address and password.
  2. Get an AuthCredential for the new authentication provider:
Google Sign-In

Web

import { GoogleAuthProvider } from "firebase/auth";
const credential = GoogleAuthProvider.credential(
googleUser.getAuthResponse().id_token);

Web

var credential = firebase.auth.GoogleAuthProvider.credential(
googleUser.getAuthResponse().id_token);

Facebook Login

Web

import { FacebookAuthProvider } from "firebase/auth";
const credential = FacebookAuthProvider.credential(
response.authResponse.accessToken);

Web

var credential = firebase.auth.FacebookAuthProvider.credential(
response.authResponse.accessToken);

Email-password sign-in

Web

import { EmailAuthProvider } from "firebase/auth";
const credential = EmailAuthProvider.credential(email, password);

Web

var credential = firebase.auth.EmailAuthProvider.credential(email, password); 3. Pass the AuthCredential object to the sign-in user'slink method:

Web

import { getAuth, linkWithCredential } from "firebase/auth";
const auth = getAuth();
linkWithCredential(auth.currentUser, credential)
.then((usercred) => {
const user = usercred.user;
console.log("Anonymous account successfully upgraded", user);
}).catch((error) => {
console.log("Error upgrading anonymous account", error);
});

Web

auth.currentUser.linkWithCredential(credential)
.then((usercred) => {
var user = usercred.user;
console.log("Anonymous account successfully upgraded", user);
}).catch((error) => {
console.log("Error upgrading anonymous account", error);
});

If the call to link succeeds, the user's new account can access the anonymous account's Firebase data.

Automatic clean-up

If you've upgraded your project to Firebase Authentication with Identity Platform, you can enable automatic clean-up in the Firebase console. When you enable this feature you allow Firebase to automatically delete anonymous accounts older than 30 days. In projects with automatic clean-up enabled, anonymous authentication will not count toward usage limits or billing quotas.

If you want to see how many users will be affected before you enable this feature, and you've upgraded your project to Firebase Authentication with Identity Platform, you can filter byis_anon in Cloud Logging.

Next steps

Now that users can authenticate with Firebase, you can control their access to data in your Firebase database usingFirebase rules.