Firebase Web Snippets

repository·master·Indexed 21 days ago

https://github.com/firebase/snippets-web

A centralized repository of version-controlled code snippets used exclusively within the official Firebase Web documentation at firebase.google.com. It contains implementation examples for Firebase services including Analytics, App Check, Authentication, Realtime Database, and Installations.

Tokens
11.6K
Snippets
63
Records
64
Agent score
73%

What's inside firebase-snippets-web

  1. Understand the purpose of Firebase Web Snippets

    master

    This repository is a collection of code snippets used exclusively within the official Firebase Web documentation at firebase.google.com.

    Note for Developers: These snippets are intended to be read in the context of a documentation page. If you want to integrate the Firebase Web SDK into your own application, do not use this repository as your primary source. Instead, use the quickstart-js repository to get started with the actual SDK implementation.

  2. How snippets are structured using region tags

    master

    Snippets in this repository are organized using specific comment markers called "region tags". This allows the documentation engine to dynamically include specific blocks of code from a single file into various documentation pages.

    To define a snippet, wrap the code with the following comments:

    • // [START tag]
    • // [END tag]

    This mechanism ensures that the code remains version-controlled on GitHub while staying synchronized with the Firebase documentation.

    // [START tag]
    // Your snippet code goes here
    // [END tag]
  3. How to include a file in the snippet separation process

    master

    To ensure a file is processed by the separate-snippets script, you must include the following comment at the top of the source file:

    // [SNIPPETS_SEPARATION enabled]

    Note: Do not edit files inside the snippets directory directly; always edit the source file indicated by the comment at the top of the generated snippet.

  4. Regenerate the snippets directory

    master

    The snippets directory is automatically generated from source files. If you have modified the source files and need to update the generated snippets, run the following command from the root of the repository.

    npm run snippets
  5. Customize the snippet name suffix

    master

    By default, separated snippets are suffixed with _modular. You can override this behavior by adding a specific comment to the source file to define a custom suffix:

    // [SNIPPETS_SUFFIX _your_custom_suffix]
    // [SNIPPETS_SUFFIX _banana]
  6. Initialize Firebase with a custom auth domain

    master

    When using a custom domain for authentication, provide the authDomain key in your firebase.initializeApp() configuration object. By default, this is set to [YOUR_APP].firebaseapp.com.

    function initializeWithCustomDomain() {
      firebase.initializeApp({
        apiKey: '...',
        // By default, authDomain is '[YOUR_APP].firebaseapp.com'.
        // You may replace it with a custom domain.
        authDomain: '[YOUR_CUSTOM_DOMAIN]'
      });
    }
  7. Initialize Firebase Storage

    master

    To use Firebase Storage, you must first initialize your Firebase App using initializeApp from firebase/app and then obtain a storage instance using getStorage from firebase/storage. The getStorage function requires your firebaseApp instance.

    const { initializeApp } = require("firebase/app");
    const { getStorage } = require("firebase/storage");
    
    const firebaseConfig = {
      apiKey: '<your-api-key>',
      authDomain: '<your-auth-domain>',
      databaseURL: '<your-database-url>',
      storageBucket: '<your-storage-bucket-url>'
    };
    
    const firebaseApp = initializeApp(firebaseConfig);
    const storage = getStorage(firebaseApp);
  8. Setup the Firebase Installations SDK

    master

    To use the Installations service, you must first import the core firebase/app module and then import the firebase/installations module to register the service with your Firebase app instance.

    import firebase from "firebase/app";
    import "firebase/installations";
  9. Initialize Firebase Performance Monitoring

    master

    To use Firebase Performance Monitoring, you must first import the firebase/app module and the firebase/performance module. After initializing your Firebase app with your project configuration, you can access the performance service using firebase.performance().

    import firebase from "firebase/app";
    import "firebase/performance";
    
    const firebaseConfig = {
      // ... your config
    };
    
    firebase.initializeApp(firebaseConfig);
    const perf = firebase.performance();
  10. Request browser notification permissions

    master

    Before retrieving a registration token, you must ensure the user has granted notification permissions using the standard Web Notification API.

    Notification.requestPermission().then((permission) => {
      if (permission === 'granted') {
        console.log('Notification permission granted.');
        // TODO(developer): Retrieve a registration token for use with FCM.
        // ...
      } else {
        console.log('Unable to get permission to notify.');
      }
    });
  11. Use User Timing Marks for performance measurement

    master

    While Firebase provides custom traces, you can also use the standard Web Performance API (window.performance) to mark specific points in time and measure the duration between them.

    const performance = window.performance;
    
    performance.mark("measurementStart");
    
    // Code that you want to trace 
    // ...
    
    performance.mark("measurementStop");
    performance.measure("customTraceName", "measurementStart", "measurementStop");
  12. Use App Check tokens with non-Firebase APIs

    master

    To protect your own backend services, you can retrieve the current App Check token using firebase.appCheck().getToken() and include it in the headers of your outgoing requests. Use the header key X-Firebase-AppCheck to pass the token string.

    const callApiWithAppCheckExample = async () => {
      let appCheckTokenResponse;
      try {
          // forceRefresh= false
          appCheckTokenResponse = await firebase.appCheck().getToken(false);
      } catch (err) {
          // Handle any errors if the token was not retrieved.
          return;
      }
    
      // Include the App Check token with requests to your server.
      const apiResponse = await fetch('https://yourbackend.example.com/yourApiEndpoint', {
          headers: {
              'X-Firebase-AppCheck': appCheckTokenResponse.token,
          }
      });
    };