Before you start

This article assumes you already have a firebase project with react-native-firebase/app installed. If you don’t know what it is, check the Getting Started section in their documents. [[React Native Firebase Documentation]](React Native Firebase | React Native Firebase (rnfirebase.io))

Installation

Install the authentication module using yarn:

1
yarn add @react-native-firebase/auth

or npm:

1
npm install @react-native-firebase/auth

If you’re developing your app using iOS, rebuild the pod

1
cd ios/ && pod install

Usage

Here are some common use of the api, which allow some basic login.

Listening to authentication state

In most scenarios using Authentication, you will want to know whether your users are currently signed-in or signed-out of your application, which is exactly what the method below do:

1
onAuthStateChanged(listener: CallbackOrObserver<AuthListenerCallback>): () => void;

It listens the changes in the users auth state (logging in & out). This method returns a unsubscribe function to stop listening to events. Always ensure you unsubscribe from the listener when no longer needed to prevent updates to components no longer in use.

Here is a common usage of thie method:

1
2
3
4
5
6
7
8
9
10
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if (user) {
// Signed in
} else {
// Signed out
}
});

// Unsubscribe from further state changes
unsubscribe();

Example:

1
2
3
4
5
6
7
8
9
10
11
12
const [user, setUser] = useState<FirebaseAuthTypes.User | null>(null);

// Handle user state changes
const onAuthStateChanged = (user: FirebaseAuthTypes.User) => {
setUser(user);
}

// Effect hook to listen to auth state changes
useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
return subscriber; // unsubscribe on unmount
}, []);

It is important to remember the onAuthStateChanged listener is asynchronous and will trigger an initial state once a connection with Firebase has been established. Therefore it is important to setup an “initializing” state which blocks render of our main application whilst the connection is established

Email/Password sign-in

Ensure the “Email/Password” sign-in provider is enabled on the Firebase Console.

image-20240125090402299

Users can both register and sign in using a method called createUserWithEmailAndPassword or sign in to an existing account with signInWithEmailAndPassword.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Sign In method
signInWithEmailAndPassword(email: string, password: string): Promise<UserCredential>;

// Sign Up method
createUserWithEmailAndPassword(email: string, password: string): Promise<UserCredential>;

// Return format [UserCredential]
{
"displayName": null,
"multiFactor": {
"enrolledFactors": []
},
"isAnonymous": false,
"emailVerified": false,
"providerData": [
{
"providerId": "password",
"uid": "xxx@gmail.com",
"email": "xxx@gmail.com"
}
],
"uid": "xxxx",
"email": "xxx@gmail.com",
"refreshToken": "xxxxx",
"tenantId": null,
"phoneNumber": null,
"photoURL": null,
"metadata": {
"creationTime": xxxx, // ISO time
"lastSignInTime": xxxx // ISO time
},
"providerId": "firebase"
}

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import auth from '@react-native-firebase/auth';

auth()
.createUserWithEmailAndPassword('jane.doe@example.com', 'SuperSecretPassword!')
.then(() => {
console.log('User account created & signed in!');
})
.catch(error => {
if (error.code === 'auth/email-already-in-use') {
console.log('That email address is already in use!');
}

if (error.code === 'auth/invalid-email') {
console.log('That email address is invalid!');
}

console.error(error);
});

This can be use with onAuthStateChanged, which allows UI switch from Login page to Account detail page if login successfully.

In case any errors occur, the module provides support for identifying what specifically went wrong by attaching a code to the error (The error.code in example above). For a full list of error codes available, view the Firebase documentation.

Signing out

If you’d like to sign the user out of their current authentication state, call the signOut method:

1
2
3
4
signOut(): Promise<void>;

// Usage
await auth.signOut();

Once successfully signed out, any onAuthStateChanged listeners will trigger an event with the user parameter being a null value.

Example:

1
2
3
4
5
import auth from '@react-native-firebase/auth';

auth()
.signOut()
.then(() => console.log('User signed out!'));

Additionally, using GoogleSignin.revokeAccess() forgets the user. This means that the next time someone signs in, they will see the account selection popup. If you don’t use this function, the last account will be automatically used without showing the account selection popup.

References

  1. Authentication | React Native Firebase (rnfirebase.io)