Integrating Expo Authentication with Firebase is a powerful way to manage user authentication in your mobile applications. This tutorial guides you through the process step-by-step, ensuring a smooth setup for your project.
Prerequisites
- Basic knowledge of React Native and Expo
- Firebase account with a created project
- Node.js and npm installed
- Expo CLI installed globally
Step 1: Set Up Firebase Project
First, create a new project in the Firebase console. Navigate to Authentication and enable the desired sign-in methods, such as Email/Password, Google, or Facebook.
Next, add your app to Firebase by registering your app's bundle ID. Download the configuration file (google-services.json for Android or GoogleService-Info.plist for iOS) and place it in your project's directory as per Firebase instructions.
Step 2: Configure Expo Project
Initialize your Expo project if you haven't already:
expo init your-project-name
Install necessary dependencies:
npm install firebase expo-auth-session
Step 3: Set Up Firebase in Your App
Create a firebase.js file in your project and initialize Firebase:
import { initializeApp } from 'firebase/app';
const firebaseConfig = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
projectId: 'YOUR_PROJECT_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
appId: 'YOUR_APP_ID',
};
const app = initializeApp(firebaseConfig);
export default app;
Step 4: Implement Authentication Methods
Use expo-auth-session to handle OAuth providers like Google. Example implementation for Google Sign-In:
import * as Google from 'expo-auth-session/providers/google';
import { getAuth, signInWithCredential, GoogleAuthProvider } from 'firebase/auth';
const auth = getAuth();
const [request, response, promptAsync] = Google.useAuthRequest({
iosClientId: 'YOUR_IOS_CLIENT_ID',
androidClientId: 'YOUR_ANDROID_CLIENT_ID',
expoClientId: 'YOUR_EXPO_CLIENT_ID',
});
useEffect(() => {
if (response?.type === 'success') {
const { id_token } = response.params;
const credential = GoogleAuthProvider.credential(id_token);
signInWithCredential(auth, credential)
.then(userCredential => {
// User signed in
})
.catch(error => {
// Handle errors
});
}
}, [response]);
Step 5: Handle User State
Listen for authentication state changes to manage user sessions:
import { onAuthStateChanged } from 'firebase/auth';
onAuthStateChanged(auth, user => {
if (user) {
// User is signed in
} else {
// User is signed out
}
});
Conclusion
By following these steps, you can successfully link Expo Authentication with Firebase for comprehensive user management. This setup allows for secure sign-in options and easy user data handling within your app.