Implementing Firebase Authentication in React Native
Course: React Native Training
Topic: Implementing Firebase Authentication
Course Link: React Native Training at JustAcademy
Demo Registration Link: Register for a Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction to Firebase Authentication
Firebase Authentication is a service provided by Google Firebase that allows developers to add secure user registration, sign-in, sign-out, and identity management to mobile and web applications. In a React Native application, Firebase Authentication can help users access personalized features without requiring the developer to build an entire authentication backend from scratch.
For example, a shopping application may allow customers to create accounts, sign in with email and password, view their order history, and manage their profile. Firebase Authentication verifies the user's identity and provides an authentication state that the application can use to determine which screens and features are available.
Firebase Authentication supports several sign-in methods, including email and password, phone authentication, and supported federated identity providers. Each method has its own configuration requirements and security considerations.
1.1 What Is Authentication?
Authentication is the process of verifying the identity of a user or client. It answers the question: "Who are you?"
In a mobile application, authentication commonly includes:
- Creating a new user account.
- Signing in with existing credentials.
- Maintaining the user's signed-in state.
- Signing out of the application.
- Recovering access when a user forgets their password.
- Verifying email addresses or phone numbers where required.
- Supporting additional identity providers when appropriate.
1.2 Authentication vs. Authorization
| Authentication |
Authorization |
| Verifies the identity of a user. |
Determines what an authenticated user is allowed to do. |
| Example: signing in with an email and password. |
Example: allowing a user to edit only their own profile. |
| Firebase Authentication manages identity and sign-in state. |
Application logic, backend checks, and Firebase Security Rules enforce access permissions. |
Successful authentication does not automatically grant access to every database record or administrative feature. Applications must implement authorization separately.
2. Learning Objectives
After completing this topic, learners should be able to:
- Explain Firebase Authentication and its role in React Native applications.
- Configure Firebase Authentication in the Firebase Console.
- Choose between React Native Firebase and the Firebase JavaScript SDK.
- Install the appropriate authentication package.
- Implement user registration with email and password.
- Implement user sign-in and sign-out.
- Observe authentication state changes.
- Build a basic login and registration interface.
- Handle authentication errors and display user-friendly messages.
- Implement password-reset functionality.
- Protect screens based on authentication state.
- Understand email verification and session persistence.
- Apply Firebase Security Rules and authentication best practices.
- Test authentication flows on supported platforms.
3. Prerequisites
Before implementing Firebase Authentication, ensure that the following requirements are satisfied:
- A working React Native application.
- Basic knowledge of JavaScript or TypeScript.
- Familiarity with React components, hooks, and asynchronous functions.
- A Google account with access to the Firebase Console.
- A Firebase project created for the application.
- The Android and/or iOS app registered with the correct application identifier.
- The Firebase configuration completed for the selected SDK.
- A suitable Android or iOS development environment for native modules when required.
If the Firebase project has not been created yet, review the official Firebase Console and the React Native Firebase documentation.
4. Understanding Firebase Authentication Architecture
Firebase Authentication manages identity verification and provides information about the currently authenticated user. The React Native application communicates with the Firebase Authentication service through the selected SDK.
4.1 Authentication Workflow
- The user opens the React Native application.
- The application checks the current authentication state.
- If the user is signed out, the application displays the sign-in or registration screen.
- The user submits credentials or chooses a supported sign-in provider.
- The application sends the authentication request through the Firebase SDK.
- Firebase verifies the request and returns an authentication result if successful.
- The application updates its interface according to the authenticated user state.
- Protected backend resources separately verify identity and enforce access rules.
4.2 Basic Authentication Flow Diagram
Open Application
|
v
Observe Authentication State
|
v
Is the User Signed In?
|
+---+---+
| |
No Yes
| |
v v
Login or Main Application
Register / Protected Screens
|
v
Submit Credentials
|
v
Firebase Authentication
|
v
Success or Error
|
v
Update UI and Authentication State
4.3 Main Components
| Component |
Purpose |
| Firebase Console |
Enables sign-in methods and manages authentication configuration. |
| Firebase SDK |
Connects the React Native application to Firebase Authentication. |
| Authentication service |
Provides registration, sign-in, sign-out, and account-management operations. |
| Authentication listener |
Notifies the application when the user's authentication state changes. |
| Application navigation |
Displays appropriate screens based on the current authentication state. |
| Security Rules or backend |
Enforces access to protected data and operations. |
5. Configuring Firebase Authentication in the Console
Before using Firebase Authentication in code, enable the sign-in provider that the application requires.
5.1 Step 1: Open Firebase Console
- Visit the Firebase Console.
- Sign in with the Google account associated with the project.
- Select the correct Firebase project.
- Verify the project name and project ID before changing any settings.
5.2 Step 2: Open Authentication
In the project dashboard, open the Authentication section. If the authentication service has not been initialized, follow the console's setup instructions.
5.3 Step 3: Enable a Sign-In Provider
- Open the sign-in methods or sign-in providers settings.
- Select Email/Password if the application uses email and password.
- Enable the required option.
- Save the changes.
Additional providers, such as Google or Apple, require provider-specific configuration. Phone authentication may require phone verification and additional platform setup.
5.4 Step 4: Review Authentication Settings
Review the available configuration options, including authorized domains for supported web-based sign-in flows, email templates, and account settings. Only configure features needed by the application.
6. Choosing the Firebase SDK for React Native
Two common approaches are the Firebase JavaScript SDK and React Native Firebase. Choose one according to your app architecture, supported Firebase features, and platform requirements.
6.1 React Native Firebase
React Native Firebase provides native Firebase integrations for React Native applications. It is commonly used in React Native CLI projects and in Expo projects configured with a suitable development build.
Install the base module:
npm install @react-native-firebase/app
Install the Authentication module:
npm install @react-native-firebase/auth
Follow the current setup guide to configure Android and iOS. Native modules must be included in a built application, so rebuild the app after making native dependency or configuration changes. React Native Firebase native modules are not available in the standard Expo Go app; use an appropriate development build for native-module support.
6.2 Firebase JavaScript SDK
The Firebase JavaScript SDK offers modular JavaScript APIs and can be used for supported Firebase functionality in compatible React Native environments.
npm install firebase
Before choosing this approach, verify the current Firebase documentation for React Native support, required persistence configuration, and the sign-in methods you intend to use.
6.3 Comparison
| Area |
React Native Firebase |
Firebase JavaScript SDK |
| API |
React Native-oriented native module APIs. |
Modular JavaScript APIs. |
| Installation |
Install the app and authentication modules. |
Install the firebase package. |
| Native setup |
Usually requires Android/iOS native configuration. |
Depends on the SDK features and React Native environment. |
| Session behavior |
Uses the native Firebase integration's authentication state handling. |
Requires supported persistence configuration appropriate to the environment. |
| Recommended approach |
Use when the required native integrations fit your project. |
Use when the required features and environment are supported. |
The examples in Sections 7–18 use React Native Firebase. Do not copy those APIs directly into a project configured only with the Firebase JavaScript SDK.
7. Installing and Verifying Firebase Authentication
7.1 Install the Packages
From the root directory of a React Native CLI project, run:
npm install @react-native-firebase/app @react-native-firebase/auth
If the packages are already installed, check the versions in package.json and ensure they are compatible with one another and with your React Native version.
7.2 Verify Native Configuration
For Android, confirm that the correct google-services.json file is placed in the Android application module and that the Google Services Gradle integration is configured according to the current documentation.
For iOS, confirm that the correct GoogleService-Info.plist file is included in the appropriate target and that the native dependencies are installed.
7.3 Rebuild the Application
After adding native modules or changing native configuration, rebuild the app. A JavaScript refresh cannot add a native module to a binary that was built before the module was installed.
For a typical React Native CLI project, the Android command may be:
npm run android
For iOS, use the project's configured iOS run script or open the iOS workspace in Xcode on macOS. Follow the current setup instructions for the React Native and Firebase versions being used.
8. Creating an Authentication Service
It is useful to place authentication operations in a separate service module. This keeps Firebase calls separate from screen presentation and reduces repeated logic across components.
8.1 Recommended Project Structure
src/
components/
AuthInput.js
LoadingIndicator.js
navigation/
AppNavigator.js
AuthNavigator.js
screens/
LoginScreen.js
RegisterScreen.js
ForgotPasswordScreen.js
HomeScreen.js
services/
authService.js
context/
AuthContext.js
This structure is an example. You can adjust it to suit the project's size, navigation library, and state-management approach.
8.2 Create authService.js
import auth from '@react-native-firebase/auth';
export async function registerWithEmail(email, password) {
return auth().createUserWithEmailAndPassword(
email.trim(),
password
);
}
export async function signInWithEmail(email, password) {
return auth().signInWithEmailAndPassword(
email.trim(),
password
);
}
export async function signOutUser() {
return auth().signOut();
}
export async function sendPasswordReset(email) {
return auth().sendPasswordResetEmail(email.trim());
}
These functions centralize common operations. Production code should also validate inputs, handle errors at an appropriate layer, and map technical error codes to clear user-facing messages.
9. Implementing User Registration
User registration allows a new user to create an account. With email-and-password authentication, the application submits the email address and password to Firebase Authentication. If the operation succeeds, Firebase returns an authentication result containing the new user.
9.1 Registration Requirements
- The Email/Password provider must be enabled in the Firebase Console.
- The email address must be provided in an acceptable format.
- The password must satisfy the project's configured password requirements.
- The application must handle duplicate accounts and network failures.
- The application should avoid logging passwords or exposing them in error reports.
9.2 Registration Function
import auth from '@react-native-firebase/auth';
export async function createAccount(email, password) {
const normalizedEmail = email.trim();
if (!normalizedEmail || !password) {
throw new Error('Email and password are required.');
}
const credential = await auth().createUserWithEmailAndPassword(
normalizedEmail,
password
);
return credential.user;
}
This example performs basic empty-field validation. A production registration flow should also provide appropriate email validation, password guidance, loading states, and safe error handling.
9.3 Registration Screen Example
import React, { useState } from 'react';
import {
View,
Text,
TextInput,
Button,
Alert,
} from 'react-native';
import auth from '@react-native-firebase/auth';
export default function RegisterScreen({ navigation }) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
async function handleRegister() {
if (!email.trim() || !password) {
Alert.alert('Missing information', 'Enter your email and password.');
return;
}
setLoading(true);
try {
await auth().createUserWithEmailAndPassword(
email.trim(),
password
);
Alert.alert('Success', 'Your account has been created.');
} catch (error) {
Alert.alert(
'Registration failed',
'We could not create your account. Check your details and try again.'
);
} finally {
setLoading(false);
}
}
return (
<View style={{ flex: 1, padding: 20, justifyContent: 'center' }}>
<Text>Create Account</Text>
<TextInput
placeholder="Email address"
value={email}
onChangeText={setEmail}
keyboardType="email-address"
autoCapitalize="none"
autoCorrect={false}
/>
<TextInput
placeholder="Password"
value={password}
onChangeText={setPassword}
secureTextEntry
/>
<Button
title={loading ? 'Creating account...' : 'Register'}
onPress={handleRegister}
disabled={loading}
/>
<Button
title="Already have an account? Sign in"
onPress={() => navigation.navigate('Login')}
/>
</View>
);
}
This example demonstrates the registration interaction. For a production interface, use a dedicated error component, stronger input validation, accessible labels, password guidance, and a consistent navigation strategy. If the authentication state listener controls navigation, avoid manually navigating to a screen that the listener will already display.
10. Implementing User Sign-In
Sign-in verifies an existing user's credentials. Once the sign-in operation succeeds, Firebase updates the authentication state, and the application can show the appropriate authenticated screens.
10.1 Sign-In Function
import auth from '@react-native-firebase/auth';
export async function loginUser(email, password) {
const normalizedEmail = email.trim();
if (!normalizedEmail || !password) {
throw new Error('Email and password are required.');
}
const result = await auth().signInWithEmailAndPassword(
normalizedEmail,
password
);
return result.user;
}
10.2 Login Screen Example
import React, { useState } from 'react';
import {
View,
Text,
TextInput,
Button,
Alert,
} from 'react-native';
import auth from '@react-native-firebase/auth';
export default function LoginScreen({ navigation }) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
async function handleLogin() {
if (!email.trim() || !password) {
Alert.alert('Missing information', 'Enter your email and password.');
return;
}
setLoading(true);
try {
await auth().signInWithEmailAndPassword(
email.trim(),
password
);
} catch (error) {
Alert.alert(
'Sign-in failed',
'Unable to sign in. Check your details or try resetting your password.'
);
} finally {
setLoading(false);
}
}
return (
<View style={{ flex: 1, padding: 20, justifyContent: 'center' }}>
<Text>Sign In</Text>
<TextInput
placeholder="Email address"
value={email}
onChangeText={setEmail}
keyboardType="email-address"
autoCapitalize="none"
autoCorrect={false}
/>
<TextInput
placeholder="Password"
value={password}
onChangeText={setPassword}
secureTextEntry
/>
<Button
title={loading ? 'Signing in...' : 'Sign In'}
onPress={handleLogin}
disabled={loading}
/>
<Button
title="Forgot Password?"
onPress={() => navigation.navigate('ForgotPassword')}
/>
<Button
title="Create an account"
onPress={() => navigation.navigate('Register')}
/>
</View>
);
}
The screen relies on an authentication-state listener to update the navigation flow after a successful sign-in. This avoids treating a successful button press as the only source of truth for whether the user is signed in.
11. Managing Authentication State
Authentication state represents whether a user is currently signed in. Firebase can restore a persisted session and notify the application when the state changes. A listener is generally preferable to checking the user only once during application startup.
11.1 Using onAuthStateChanged
import auth from '@react-native-firebase/auth';
const unsubscribe = auth().onAuthStateChanged(user => {
if (user) {
console.log('Authenticated user detected');
} else {
console.log('No authenticated user');
}
});
// Call unsubscribe when the listener is no longer needed.
unsubscribe();
The listener returns an unsubscribe function. In a React component, attach the listener in an effect and clean it up when the component unmounts. Avoid logging unnecessary personal information about the authenticated user.
11.2 Create an Authentication Context
An authentication context allows multiple screens to access the current user and authentication initialization status without passing props through every component.
import React, {
createContext,
useContext,
useEffect,
useState,
} from 'react';
import auth from '@react-native-firebase/auth';
const AuthContext = createContext({
user: null,
initializing: true,
});
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const [initializing, setInitializing] = useState(true);
useEffect(() => {
const unsubscribe = auth().onAuthStateChanged(currentUser => {
setUser(currentUser);
if (initializing) {
setInitializing(false);
}
});
return unsubscribe;
}, [initializing]);
return (
<AuthContext.Provider value={{ user, initializing }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
return useContext(AuthContext);
}
This example illustrates the main concept. A production implementation can refine the effect dependencies and initialization handling to keep the subscription lifecycle simple. The listener should be registered once per provider lifecycle and cleaned up when the provider unmounts.
11.3 Use the Provider in the App
import React from 'react';
import { AuthProvider } from './src/context/AuthContext';
import AppNavigator from './src/navigation/AppNavigator';
export default function App() {
return (
<AuthProvider>
<AppNavigator />
</AuthProvider>
);
}
11.4 Why Initialization State Matters
When the application starts, the authentication SDK may need time to determine whether a session exists. During this period, the application should show a loading screen or splash screen instead of briefly displaying the wrong navigation stack.
12. Implementing Sign-Out
Sign-out ends the user's local authenticated session through Firebase Authentication. The application should update its interface when the authentication listener reports that no user is signed in.
12.1 Sign-Out Function
import auth from '@react-native-firebase/auth';
export async function logoutUser() {
await auth().signOut();
}
12.2 Sign-Out Button
import React, { useState } from 'react';
import { Button, Alert } from 'react-native';
import auth from '@react-native-firebase/auth';
export default function LogoutButton() {
const [loading, setLoading] = useState(false);
async function handleLogout() {
setLoading(true);
try {
await auth().signOut();
} catch (error) {
Alert.alert('Error', 'Unable to sign out. Please try again.');
} finally {
setLoading(false);
}
}
return (
<Button
title={loading ? 'Signing out...' : 'Sign Out'}
onPress={handleLogout}
disabled={loading}
/>
);
}
When sign-out succeeds, the authentication-state listener should update the application and display the signed-out screens. If the application uses additional local caches or application-specific session data, clear or invalidate those values as appropriate.
13. Implementing Password Reset
Users may forget their passwords. Firebase Authentication provides a password-reset email operation for supported email-and-password accounts.
13.1 Password Reset Function
import auth from '@react-native-firebase/auth';
export async function requestPasswordReset(email) {
const normalizedEmail = email.trim();
if (!normalizedEmail) {
throw new Error('Email address is required.');
}
await auth().sendPasswordResetEmail(normalizedEmail);
}
13.2 Password Reset Screen Example
import React, { useState } from 'react';
import {
View,
Text,
TextInput,
Button,
Alert,
} from 'react-native';
import auth from '@react-native-firebase/auth';
export default function ForgotPasswordScreen() {
const [email, setEmail] = useState('');
const [loading, setLoading] = useState(false);
async function handleReset() {
if (!email.trim()) {
Alert.alert('Email required', 'Enter your email address.');
return;
}
setLoading(true);
try {
await auth().sendPasswordResetEmail(email.trim());
Alert.alert(
'Check your email',
'If the address is eligible, password-reset instructions will be sent.'
);
} catch (error) {
Alert.alert(
'Request could not be completed',
'Please check the address and try again later.'
);
} finally {
setLoading(false);
}
}
return (
<View style={{ flex: 1, padding: 20, justifyContent: 'center' }}>
<Text>Reset Password</Text>
<TextInput
placeholder="Email address"
value={email}
onChangeText={setEmail}
keyboardType="email-address"
autoCapitalize="none"
autoCorrect={false}
/>
<Button
title={loading ? 'Sending...' : 'Send Reset Email'}
onPress={handleReset}
disabled={loading}
/>
</View>
);
}
For privacy, use a neutral confirmation message where appropriate so the interface does not reveal whether a particular email address has an account. Firebase's email-enumeration protection and project settings may affect which errors are returned.
14. Email Verification
Email verification helps confirm that a user can access the email address associated with an account. It can be useful before allowing certain sensitive actions.
14.1 Send a Verification Email
import auth from '@react-native-firebase/auth';
export async function sendVerificationEmail() {
const user = auth().currentUser;
if (!user) {
throw new Error('You must be signed in.');
}
await user.sendEmailVerification();
}
14.2 Check Verification Status
import auth from '@react-native-firebase/auth';
export async function refreshVerificationStatus() {
const user = auth().currentUser;
if (!user) {
return false;
}
await user.reload();
return auth().currentUser?.emailVerified ?? false;
}
After a user opens the verification link, refresh the user's profile before checking the updated verification state. A verified email is not a substitute for authorization checks on protected backend resources.
15. Handling Authentication Errors
Authentication operations can fail for many reasons, including invalid credentials, unavailable networks, disabled providers, rate limits, and incorrect project configuration. The application should handle expected failures and display messages that users can understand.
15.1 Common Error Categories
| Error Category |
Possible Reason |
Recommended Response |
| Invalid credentials |
Email or password is incorrect. |
Ask the user to check the details or reset the password. |
| Email already in use |
An account already exists for the address. |
Offer sign-in or account recovery. |
| Weak password |
Password does not satisfy the configured requirements. |
Explain the password requirements. |
| Invalid email |
Email address is malformed. |
Ask the user to enter a valid address. |
| Network failure |
The device cannot reach the service. |
Check connectivity and allow the user to retry. |
| Too many requests |
Requests may have exceeded a limit. |
Ask the user to wait and retry later. |
| Provider disabled |
The sign-in method is not enabled. |
Review the Firebase Console provider settings. |
| Permission denied |
A separate database or storage rule blocks an operation. |
Review authorization logic and the applicable Security Rules. |
15.2 Map Technical Errors to Safe Messages
export function getAuthErrorMessage(error) {
switch (error?.code) {
case 'auth/invalid-email':
return 'Enter a valid email address.';
case 'auth/email-already-in-use':
return 'An account may already exist for this email. Try signing in.';
case 'auth/weak-password':
return 'Choose a stronger password.';
case 'auth/user-disabled':
return 'This account is currently unavailable. Contact support if needed.';
case 'auth/network-request-failed':
return 'Check your internet connection and try again.';
case 'auth/too-many-requests':
return 'Too many attempts. Please wait before trying again.';
default:
return 'The request could not be completed. Please try again.';
}
}
Error codes can vary by SDK version, provider, and authentication settings. Confirm the codes relevant to the installed SDK. Avoid revealing account existence, sensitive internal details, stack traces, or raw error messages to end users.
16. Protecting Screens with Authentication State
Authentication state can be used to decide which navigation flow the user sees. For example, signed-out users may see login and registration screens, while signed-in users see the main application.
16.1 Conditional Navigation Example
import React from 'react';
import { View, Text, ActivityIndicator } from 'react-native';
import { useAuth } from '../context/AuthContext';
import AuthNavigator from './AuthNavigator';
import MainNavigator from './MainNavigator';
export default function AppNavigator() {
const { user, initializing } = useAuth();
if (initializing) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<ActivityIndicator size="large" />
<Text>Checking session...</Text>
</View>
);
}
return user ? <MainNavigator /> : <AuthNavigator />;
}
AuthNavigator and MainNavigator represent navigation components that you create using your chosen navigation library. This pattern keeps the signed-in and signed-out flows separate.
16.2 Important Security Principle
Protecting a screen in the user interface is not sufficient to protect private data. A user can inspect or modify a client application. Firebase Security Rules and trusted backend authorization must independently verify access to sensitive records and operations.
17. Using Firebase Authentication with Firestore
Authentication and Cloud Firestore are often used together. Authentication identifies the user, while Firestore Security Rules determine which documents that user may access.
17.1 Example: Store a User Profile
import auth from '@react-native-firebase/auth';
import firestore from '@react-native-firebase/firestore';
export async function createUserProfile(displayName) {
const user = auth().currentUser;
if (!user) {
throw new Error('User must be signed in.');
}
await firestore()
.collection('users')
.doc(user.uid)
.set({
displayName,
email: user.email ?? null,
createdAt: firestore.FieldValue.serverTimestamp(),
}, { merge: true });
}
The user ID comes from the Firebase-authenticated user rather than from an arbitrary value entered in a form. The corresponding Firestore Security Rules must still restrict the user to permitted documents and fields.
17.2 Example Security Rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read: if request.auth != null
&& request.auth.uid == userId;
allow create, update: if request.auth != null
&& request.auth.uid == userId;
}
}
}
This is a basic ownership example. For production, validate permitted fields, prevent users from assigning themselves privileged roles, and test all access scenarios. Administrative roles should not be granted merely because a client writes a field such as isAdmin: true.
18. Authentication State and Session Persistence
Firebase Authentication SDKs can persist user authentication state according to the selected platform and SDK. The application should use the SDK's supported session handling rather than storing a user's password in local storage.
18.1 Important Practices
- Never store plaintext passwords in AsyncStorage or other client storage.
- Do not manually copy authentication tokens into logs or analytics events.
- Use the selected SDK's supported session and token handling.
- Rebuild and test the application after native configuration changes.
- Handle token refresh and authentication-state changes through the SDK.
- Require reauthentication for sensitive account operations when appropriate.
- Clear application-specific private caches after sign-out.
18.2 Authentication Persistence Is Not Authorization
A persisted session can make it possible for a user to remain signed in between app launches. It does not mean that every action should be allowed. Backend services and Firebase Security Rules must check identity and permissions for protected operations.
19. Security Best Practices
- Use Firebase Authentication rather than creating a custom password-storage system without appropriate security expertise.
- Require strong passwords and follow current Firebase password-policy options where available.
- Enable only the sign-in providers required by the application.
- Use email verification or multi-factor authentication when appropriate to the risk.
- Use neutral error messages where revealing account existence could create a privacy risk.
- Apply restrictive Firestore, Realtime Database, and Storage Security Rules.
- Never include service-account private keys in React Native source code or application bundles.
- Do not log passwords, access tokens, or other sensitive authentication material.
- Use secure transport and avoid sending credentials to untrusted endpoints.
- Keep Firebase SDK dependencies updated and review relevant release notes.
- Test sign-in, sign-out, session restoration, account recovery, and unauthorized access.
- Consider App Check and other abuse-prevention controls where suitable; these complement rather than replace authentication and authorization.
20. Testing Firebase Authentication
Testing ensures that authentication works as expected across the different user journeys and failure scenarios.
20.1 Functional Test Cases
| Test Case |
Action |
Expected Result |
| Registration |
Register with a valid email and password. |
The account is created and authentication state updates. |
| Duplicate account |
Register with an address already in use. |
The operation is handled safely with an appropriate message. |
| Sign-in |
Sign in with valid credentials. |
The authenticated navigation flow appears. |
| Invalid sign-in |
Submit incorrect credentials. |
The user sees a safe error message. |
| Sign-out |
Press the sign-out button. |
The signed-out navigation flow appears. |
| Password reset |
Request a password-reset email. |
The interface displays a suitable confirmation. |
| Session restoration |
Close and reopen the application. |
The SDK restores or reports the current state appropriately. |
| Protected data |
Attempt to access another user's document. |
Security Rules deny unauthorized access. |
| Offline or network failure |
Disable connectivity during an authentication operation. |
The app handles the failure without crashing. |
20.2 Firebase Emulator Suite
The Firebase Emulator Suite provides local emulators for supported Firebase services, including Authentication and Firestore. It can help developers test registration, sign-in, and authorization behavior without using production data.
Official resource: Firebase Emulator Suite Documentation.
Configure emulator usage deliberately in development and ensure that production builds do not accidentally connect to local emulator addresses.
21. Common Problems and Troubleshooting
| Problem |
Possible Cause |
Solution |
| Authentication provider not enabled |
The selected provider is disabled in Firebase Console. |
Enable the provider and review any required configuration. |
| Module not found |
Package missing or incorrect import path. |
Install the correct package and verify the import. |
| Native module unavailable |
The application was not rebuilt after installation. |
Rebuild the native application and check linking or configuration. |
| Registration fails |
Invalid input, password policy, network problem, or account conflict. |
Validate input and inspect the error code safely. |
| Login fails repeatedly |
Incorrect credentials, disabled user, rate limiting, or project mismatch. |
Check the Firebase project and provider settings; use account recovery when appropriate. |
| Wrong Firebase project is used |
Incorrect platform configuration file or environment selection. |
Verify the project ID and app identifier for the active build. |
| Screen does not update after login |
Authentication state is not observed or navigation state is managed incorrectly. |
Use a properly cleaned-up authentication listener and conditional navigation. |
| Firestore request is denied |
Security Rules do not allow the operation. |
Check the current authenticated user, document ownership, and rule conditions. |
| Password reset is not received |
Email delivery, address, provider configuration, or email template issue. |
Review the address, spam folder, Firebase email settings, and available logs. |
| Authentication state is lost unexpectedly |
SDK configuration, app lifecycle, sign-out logic, or persistence assumptions. |
Review the chosen SDK's persistence behavior and test a clean app restart. |
22. Practical Project: Build a Firebase Login Application
Build a simple React Native application with registration, login, password reset, a protected home screen, and sign-out.
22.1 Project Features
- Registration using email and password.
- Login using existing credentials.
- Authentication state management.
- Conditional navigation for signed-in and signed-out users.
- Password-reset email request.
- Sign-out functionality.
- Loading indicators and safe error messages.
- Optional email verification.
- Optional Firestore user profile storage with Security Rules.
22.2 Suggested Implementation Steps
- Create the Firebase project and register the mobile application.
- Enable the Email/Password sign-in provider.
- Install the required Firebase SDK modules.
- Complete Android and/or iOS configuration.
- Create an authentication service module.
- Build the registration and login screens.
- Implement password-reset functionality.
- Create an authentication context or equivalent state-management layer.
- Configure conditional navigation and a startup loading screen.
- Build a protected home screen with a sign-out button.
- Test all authentication success and failure cases.
- Configure Security Rules before connecting private application data.
22.3 Expected Result
The application should allow a user to register, sign in, remain signed in according to the selected SDK's session behavior, and sign out. Navigation should respond to the authentication state, while protected backend resources remain secured by their own authorization rules.
23. Interview Questions and Answers
Q1. What is Firebase Authentication?
Firebase Authentication is a service for managing user identity, registration, sign-in, and supported account-management operations.
Q2. How do you enable email-and-password authentication?
Open the Firebase Console, select the project, open Authentication, enable the Email/Password provider, and save the configuration.
Q3. What is the purpose of onAuthStateChanged?
It listens for changes in the user's authentication state, allowing the app to respond to sign-in, sign-out, and session restoration.
Q4. Why should authentication logic be separated into a service?
A service module centralizes Firebase calls, reduces duplicated logic, and makes authentication operations easier to maintain and test.
Q5. How do you register a user with React Native Firebase?
Use auth().createUserWithEmailAndPassword(email, password) after configuring the project and enabling the appropriate provider.
Q6. How do you sign in an existing user?
Use auth().signInWithEmailAndPassword(email, password) and handle the result or error appropriately.
Q7. How do you sign out?
Call auth().signOut() and let the authentication listener update the application's navigation state.
Q8. How does password reset work?
The application calls auth().sendPasswordResetEmail(email). Firebase handles the reset-email workflow according to the project's configuration.
Q9. What is email verification?
Email verification confirms that a user can access the email address associated with an account. It can be used as a requirement for selected features.
Q10. What is the difference between authentication and authorization?
Authentication verifies identity, while authorization determines what that identity is allowed to access or change.
Q11. Why is an authentication loading state needed?
The SDK may need time to determine the current session when the application starts. A loading state prevents the wrong navigation flow from flashing on the screen.
Q12. Should passwords be saved in AsyncStorage?
No. Applications should not store plaintext passwords in AsyncStorage or other ordinary client storage. Use the authentication SDK's supported session management.
Q13. Does hiding a screen secure its data?
No. The database, storage service, or backend must independently enforce authorization through Security Rules or server-side checks.
Q14. What is the Firebase Emulator Suite?
It provides local emulators for supported Firebase services, helping developers test authentication and other Firebase workflows in development.
Q15. What should happen after sign-out?
The authentication listener should report that no user is signed in, and the application should show the signed-out navigation flow and clear any application-specific private data that is no longer needed.
24. Quick Revision Notes
- Firebase Authentication manages identity and sign-in state.
- Enable the required sign-in provider in the Firebase Console.
- Choose the Firebase SDK that matches the project's needs.
- Install and configure the required packages for the selected SDK.
- Use registration APIs to create accounts.
- Use sign-in APIs to authenticate existing users.
- Observe authentication state to update the application UI.
- Use sign-out to end the authenticated session.
- Provide password-reset functionality where appropriate.
- Use email verification when the application requires it.
- Map technical errors to safe and understandable user messages.
- Protect private records with Firebase Security Rules or backend authorization.
- Never store plaintext passwords or embed privileged server credentials in the app.
- Test session restoration, network failures, and unauthorized requests.
25. Best Practices for Production Applications
- Keep Firebase dependencies compatible and updated.
- Use environment-specific Firebase projects when appropriate.
- Validate user input before submitting authentication requests.
- Disable duplicate form submissions while a request is in progress.
- Provide accessible labels and clear validation feedback.
- Do not reveal sensitive account details in error messages.
- Use an authentication listener as the source of truth for signed-in state.
- Clean up listeners when their owning component or provider unmounts.
- Require reauthentication for sensitive account operations where supported and appropriate.
- Use restrictive Firestore, Realtime Database, and Storage Security Rules.
- Never trust client-provided role fields for privileged authorization decisions.
- Do not log passwords, authentication tokens, or private account details.
- Test on the actual platforms and build configurations supported by the project.
- Use the Firebase Emulator Suite for appropriate local testing.
- Review official documentation when APIs, SDK requirements, or provider settings change.
26. Official Learning Resources
27. Conclusion
Firebase Authentication simplifies user identity management in React Native applications by providing registration, sign-in, sign-out, password recovery, and other supported account-management features. A successful implementation requires more than calling an authentication method: the Firebase project and sign-in provider must be configured correctly, authentication state must be managed consistently, and errors must be handled safely.
For a reliable application, use the appropriate Firebase SDK, observe authentication-state changes, show the correct navigation flow, and protect private backend data with Security Rules or server-side authorization. Never rely only on client-side navigation to secure sensitive information.
Explore the course: React Native Training at JustAcademy
Register for a demo: JustAcademy Course Demo Registration
Visit the website: JustAcademy Official Website