Setting Up Firebase with Capacitor: A Complete Guide

2024-10-30 | StealthWork Team

Mobile Development

Getting Started with Firebase and Capacitor

Firebase provides powerful backend services for mobile applications. In this guide, we'll walk through integrating Firebase with your Capacitor app, focusing on authentication and basic setup.

Prerequisites

Before starting, ensure you have the following: Node.js installed, a Capacitor project set up, and Android Studio for Android development. You'll also need a Google account to access Firebase Console.
bash
npm install @capacitor-firebase/authentication firebase
npx cap sync

Creating a Firebase Project

Start by creating a new Firebase project in the Firebase Console. Navigate to the console, click 'Add Project', and follow the setup wizard. Make sure to enable the services you plan to use, such as Authentication, Firestore, or Realtime Database.

Android Setup: Using Android Studio

The easiest way to connect your Android app to Firebase is using Android Studio's Firebase Assistant. Open your Android project in Android Studio by running 'npx cap open android', then follow these steps:
  1. In Android Studio, go to Tools > Firebase
  2. Click on Authentication > Get Started with Firebase Auth
  3. Click 'Connect to Firebase' and select your Firebase project
  4. Android Studio will automatically add the necessary dependencies

Manual Android Setup

If you prefer manual setup, you'll need to add the google-services.json file to your project. Download it from the Firebase Console and place it in the correct location:
bash
# Place google-services.json in:
android/app/google-services.json

Update Android Configuration

Add the Firebase SDK to your Android project by modifying the following files:
gradle
// android/build.gradle
buildscript {
  dependencies {
    classpath 'com.google.gms:google-services:4.3.15'
  }
}

// android/app/build.gradle
apply plugin: 'com.google.gms.google-services'

dependencies {
  implementation platform('com.google.firebase:firebase-bom:32.2.0')
  implementation 'com.google.firebase:firebase-auth'
}

Capacitor Plugin Installation

Install the necessary Capacitor Firebase plugins for the services you plan to use. For this example, we'll focus on authentication:
typescript
// capacitor.config.ts
import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  plugins: {
    FirebaseAuthentication: {
      skipNativeAuth: false,
      providers: ['google.com', 'apple.com', 'facebook.com']
    }
  }
};

export default config;

Implementing Firebase Authentication

Here's a basic example of implementing Google Sign-In with Firebase:
typescript
import { FirebaseAuthentication } from '@capacitor-firebase/authentication';

async function signInWithGoogle() {
  try {
    const result = await FirebaseAuthentication.signInWithGoogle();
    console.log('User:', result.user);
    return result.user;
  } catch (error) {
    console.error('Sign-in failed:', error);
    throw error;
  }
}

async function signOut() {
  await FirebaseAuthentication.signOut();
  console.log('User signed out');
}

State Management

Track authentication state changes using the provided listener:
typescript
import { FirebaseAuthentication } from '@capacitor-firebase/authentication';

FirebaseAuthentication.addListener('authStateChange', (change) => {
  if (change.user) {
    console.log('User is signed in:', change.user);
  } else {
    console.log('User is signed out');
  }
});

Troubleshooting Common Issues

If you encounter SHA-1 or SHA-256 related errors with Google Sign-In, you'll need to add your debug and release key fingerprints to your Firebase project. You can find these in Android Studio under:
  1. Open Android Studio
  2. Navigate to Tools > App Links Assistant
  3. Click 'Open Signing Report'
  4. Copy the SHA-1 and SHA-256 values
  5. Add these to your Firebase Console under Project Settings > Your Apps > Android Apps > Add Fingerprint

Testing Your Integration

Before deploying, test your Firebase integration thoroughly. Make sure to test both development and production configurations:
bash
# Build and run your app
npm run build
npx cap sync
npx cap open android

Conclusion

You now have a working Firebase integration in your Capacitor app. Remember to handle error cases appropriately and implement proper security rules in your Firebase Console. For production deployment, ensure you've configured proper authentication providers and have added all necessary SHA fingerprints to your Firebase project.