Capacitor Firebase

repository·main·Indexed 19 days ago

https://github.com/capawesome-team/capacitor-firebase

A suite of Capacitor plugins for integrating Firebase services into Android, iOS, and Web applications. Includes plugins such as @capacitor-firebase/analytics for event tracking, user identification, and consent management, and @capacitor-firebase/app-check for app attestation and token management.

Tokens
79.8K
Snippets
265
Records
406
Agent score
65%

What's inside capacitor-firebase

  1. Overview of Capacitor Firebase

    main

    Capacitor Firebase is a collection of Capacitor plugins designed to integrate Firebase services into Capacitor projects. It provides a unified way to access Firebase features across multiple platforms.

    Key Features

    • Platform Support: Works on Android, iOS, and the Web.
    • Capacitor Compatibility: Supports Capacitor 8.
    • Firebase Web SDK Support: Compatible with the modular Firebase Web SDK.
    • Consistent Versioning: Designed to prevent SDK version conflicts.
    • TypeScript Support: Provides unified TypeScript definitions for a better developer experience.
  2. Configure Firestore queries with filters and constraints

    main

    When using getCollection, getCollectionGroup, or getCountFromServer, you can refine results using compositeFilter and queryConstraints.

    Filters (compositeFilter)

    Use QueryCompositeFilterConstraint to combine filters with 'and' or 'or' logic. A filter is defined by a QueryFieldFilterConstraint specifying a fieldPath, an opStr (operator), and a value.

    Supported Operators (QueryOperator): '<', '<=', '==', '>=', '>', '!=', 'array-contains', 'array-contains-any', 'in', 'not-in'

    Constraints (queryConstraints)

    Use QueryNonFilterConstraint to narrow or order results:

    • orderBy: Sort by a field using OrderByDirection ('asc' or 'desc').
    • limit / limitToLast: Restrict the number of returned items.
    • startAt / startAfter: Pagination starting from a specific document reference.
    • endAt / endBefore: Pagination ending at a specific document reference.
  3. Protect your backend with App Check tokens

    main

    To protect your own backend services, retrieve the current App Check token in JWT format using the getToken() method. You should include this token in the headers of your requests to your backend. On your server, you can then verify the token to ensure the request originated from a legitimate, verified app instance.

    You can also use the tokenChanged listener to be notified whenever the App Check token is updated.

  4. Understand the Firebase SDK Update Versioning Policy

    main

    The capacitor-firebase plugins follow a specific versioning policy to determine whether a Firebase SDK update results in a Minor or Major plugin release. This policy is designed to minimize unnecessary major version bumps while ensuring that breaking changes (like SDK major bumps or API changes) are clearly signaled to developers.

    Minor Release Criteria

    A plugin update is released as a Minor version only if all the following are true:

    • The Firebase SDK upgrade is a minor or patch update (maintaining the same major version) across Web, iOS, and Android.
    • No plugin imports a Web SDK symbol that was introduced after the current firebase peerDependency floor.
    • There are no changes to the plugin's Android minSdkVersion, compileSdkVersion, targetSdkVersion, or the iOS deployment target.
    • There are no changes to the plugin's TypeScript API surface or observable runtime behavior.

    Major Release Criteria

    A plugin update is released as a Major version if any of the following occur:

    • A Firebase SDK major version bump occurs on any platform (Web, iOS, or Android).
    • The Android minSdkVersion or the iOS deployment target is raised.
    • The plugin's TypeScript API surface or runtime behavior changes.
    • The firebase peerDependency floor is raised (excluding previously supported versions).

    Note: If an update contains a mix of minor and major qualifying changes, it is released as a Major version.

    Important Notes for Consumers

    • Toolchain Bumps: Updates to build-time toolchains (e.g., requiring a newer version of Xcode or Swift) are considered non-breaking for app consumers but will be noted in the release notes.
    • Release Notes: Always check the release notes to identify the specific new versions of the Firebase JS, iOS, and Android SDKs being used.
  5. Synchronize Native and Web Authentication

    main

    To achieve a unified session, you must perform a two-step authentication process:

    1. Native Layer: Call the appropriate FirebaseAuthentication method to obtain credentials (like idToken, accessToken, or nonce) from the native OS.
    2. Web Layer: Use the Firebase JS SDK's signInWithCredential method with the credentials obtained from the native layer.

    This pattern applies to most providers including Google, Facebook, Apple, Twitter, and Phone authentication.

    // Example: Google Sign-In synchronization
    const signInWithGoogle = async () => {
      // 1. Create credentials on the native layer
      const result = await FirebaseAuthentication.signInWithGoogle();
      // 2. Sign in on the web layer using the id token
      const credential = GoogleAuthProvider.credential(result.credential?.idToken);
      const auth = getAuth();
      await signInWithCredential(auth, credential);
    };
  6. Understand the difference between native and web authentication

    main

    The plugin provides two ways to handle authentication:

    1. Native Authentication: Uses the Firebase SDKs for Java (Android) and Swift (iOS). This provides full functionality and supports native social providers (Apple, Google, etc.). Note that after a native login, the user is only logged in at the native layer. If you need to access Firebase services via the Firebase JS SDK (like Cloud Firestore) in the web layer, you must perform additional synchronization steps.

    2. Web Implementation: Encapsulates the Firebase JS SDK to provide a consistent interface across all platforms. While easier to use, it has limited functionality on Android and iOS within WebViews due to OAuth interaction restrictions in native apps.

  7. Add metrics and attributes to a trace

    main

    You can enrich your performance traces with additional data to provide context or quantitative measurements.

    Metrics

    Metrics are numeric values associated with a trace (e.g., a counter for cache hits).

    • Use putMetric(...) to set a value.
    • Use incrementMetric(...) to increase a value.
    • Note: Metric values are floored down to the nearest integer.

    Attributes

    Attributes are string values associated with a trace (e.g., a user ID). These are used to segment and filter your performance data in the Firebase console.

  8. Fetch and activate Remote Config values

    main

    Remote Config values are not immediately available after fetching. You must activate the fetched configuration before the getters can return the remote values.

    You have two ways to handle this:

    1. Two-step process: Call fetchConfig(...) followed by activate().
    2. One-step process: Call fetchAndActivate() to perform both operations at once.

    If you attempt to use getters before activation, they will return the default values instead of the remote ones.

  9. Compare Capacitor Firebase Cloud Messaging vs Capacitor Push Notifications

    main

    The @capacitor-firebase/messaging plugin uses the Firebase SDK for Android, iOS, and Web. It provides more advanced features than the standard Capacitor Push Notifications plugin, including:

    • Topic Subscriptions: Ability to subscribe to and unsubscribe from specific messaging topics.
    • Foreground Notifications: The ability to receive and handle notifications while the app is actively in the foreground.
    • Cross-Platform Firebase SDK: Uses the native Firebase SDKs for all supported platforms.