Use Firebase in Progressive Web Apps

Progressive Web Apps (PWAs) are web apps that follow a set of guidelines meant to ensure that your users have a reliable, fast, and engaging experience.

Firebase offers several services that can help you efficiently add progressive features to your app to meet many PWA best practices, including:

PWA best practice How Firebase services can help
Safe and secure
  • Firebase Hosting provisions free SSL certificates for your custom domain and default Firebase subdomain.
  • Firebase Authentication enables you to sign in users across devices securely.
  • FirebaseUI implements best practices for authentication flows.
Fast load time
  • Firebase Hosting supports HTTP/2 and can cache both your static and dynamic content on a global CDN.
  • The Firebase JavaScript SDK is modular, and you can dynamically import libraries when they're needed.
Network resilience
  • With Cloud Firestore, you can store and access data in real time and offline.
  • Firebase Authentication maintains a user's authentication state, even offline.
Engage users
  • Firebase Cloud Messaging enables you to send push messages to your users' devices.
  • With Cloud Functions for Firebase, you can automate re-engagement messages based on cloud events.

This page offers an overview of how the Firebase platform can help you to build a modern, high-performance PWA using our cross-browser Firebase JavaScript SDK.

For an example of using Firebase to create a PWA, have a look at our open-source sample application FriendlyPix. Visit our getting started guide to add Firebase to your web app.

Safe and secure

From serving your site to implementing an authentication flow, it's critical that your PWA provides a secure and trusted workflow.

Serve your PWA over HTTPS

Performant hosting service

HTTPS protects the integrity of your website and protects the privacy and security of your users. PWAs must be served over HTTPS.

Firebase Hosting, by default, serves your app's content over HTTPS. You can serve your content on a free Firebase-subdomain or on your own custom domain. Our hosting service provisions an SSL certificate for your custom domain automatically and for free.

Visit the getting started guide for Firebase Hosting to learn how you can host your PWA on the Firebase platform.

Offer a secure authentication flow

FirebaseUI provides a drop-in responsive authentication flow based on Firebase Authentication, allowing your app to integrate a sophisticated and secure sign-in flow with low effort. FirebaseUI automatically adapts to the screen size of a user's devices and follows best practices for auth flows.

Drop-in responsive authentication flow

FirebaseUI supports multiple sign-in providers. Add the FirebaseUI auth flow into your app with just a few lines of code configured for sign-in providers:

// FirebaseUI config.
var uiConfig = {
  signInSuccessUrl: 'url-to-redirect-to-on-success',
  signInOptions: [
    firebase.auth.GoogleAuthProvider.PROVIDER_ID,
    firebase.auth.EmailAuthProvider.PROVIDER_ID
  ]
};

// Initialize the FirebaseUI widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());
ui.start('#firebaseui-auth-container', uiConfig);

Visit our documentation in GitHub to learn more about the various configuration options offered by FirebaseUI.

Sign in users across devices

Sign-in across devices

By using FirebaseUI to integrate one-tap sign in, your app can automatically sign in users, even on different devices that they've set up with their sign-in credentials.

Enable one-tap sign-in using FirebaseUI by changing one line of configuration:

// FirebaseUI config.
var uiConfig = {
  signInSuccessUrl: 'url-to-redirect-to-on-success',
  authMethod: 'https://accounts.google.com',
  signInOptions: firebase.auth.GoogleAuthProvider.PROVIDER_ID,
  // Enable one-tap sign-in.
  credentialHelper: firebaseui.auth.CredentialHelper.GOOGLE_YOLO
};

Visit our documentation in GitHub to learn more about the various configuration options offered by FirebaseUI.

Fast load time

Having great performance improves the user experience, helps retain users, and increases conversion. Great performance, such as low "time to first meaningful paint" and "time to interactive", is an important requirement for PWAs.

Serve your static assets efficiently

Performant hosting service

Firebase Hosting serves your content over a global CDN and is HTTP/2 compatible. When you host your static assets with Firebase, we configure all this for you -- there's nothing extra that you need to do to take advantage of this service.

Cache your dynamic content

With Firebase Hosting, your web app can also serve dynamic content that's generated server-side by Cloud Functions or a Cloud Run containerized app. Using this service, you can cache your dynamic content on a powerful global CDN with one line of code:

res.set('Cache-Control', 'public, max-age=300, s-maxage=600');

This service allows you to avoid additional calls to your back-end, speed up responses, and decrease costs.

Visit our documentation to learn how you can serve dynamic content (powered by Cloud Functions or Cloud Run) and enable CDN-caching with Firebase Hosting.

Load services only when they're needed

The Firebase JavaScript SDK can be partially imported to keep initial download size minimal. Take advantage of this modular SDK to import the Firebase services that your app needs only when they're needed.

For example, to increase your app's initial paint speed your app can first load Firebase Authentication. Then, when your app needs them, you can load other Firebase services, like Cloud Firestore.

Using a package manager such as webpack, you can first load Firebase Authentication:

import firebase from 'firebase/app';
import 'firebase/auth';

// Load Firebase project configuration.
const app = firebase.initializeApp(firebaseConfig);

Then, when you need to access your data layer, load the Cloud Firestore library using dynamic imports:

import('firebase/firestore').then(() => {
  const firestore = app.firestore();
  // Use Cloud Firestore ...
});

To see an example of partial and dynamic imports with Firebase, take a look at our open-source sample application FriendlyPix which demonstrates this technique.

Network resilience

Your users might not have dependable internet access. PWAs should behave similar to native mobile apps and should function offline whenever possible.

Access your app data offline

Cloud Firestore supports offline data persistence which enables your app's data layer to transparently work offline. Combined with Service Workers to cache your static assets, your PWA can fully function offline. You can enable offline data persistence with one line of code:

firebase.firestore().enablePersistance().then(() => {
  const firestore = app.firestore();
  // Use Cloud Firestore ...
});

Maintain auth state offline

Firebase Authentication keeps a local cache of sign-in data, allowing a previously signed-in user to remain authenticated even when they're offline. The sign-in state observer will function normally and trigger even if your user reloads the app while offline:

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User is signed-in ...
  } else {
    // User is signed out ...
  }
});

Visit our documentation to get started with Cloud Firestore and Firebase Authentication.

Engage users

Your users want to know when you release new features for your app, and you want to keep user engagement high. Set up your PWA to proactively and responsibly reach out to your users.

Display push notifications to your users

With Firebase Cloud Messaging, you can push relevant notifications from your server to your users' devices. This service allows you to display timely notifications to your users even when the app is closed.

Automate user re-engagement

Using Cloud Functions for Firebase, send your users re-engagement messages based on cloud events, for example a data write to Cloud Firestore or a user account deletion. You can also send a push notification to a user when that user gets a new follower:

// Send push notification when user gets a new follower.
exports.sendNotification = functions.database.ref('/followers/{userUID}/{followerUID}')
    .onWrite((change, context) => {
      const userUID = context.params.userUID;
      const followerUID = context.params.followerUID;

      const tokens = getUserDeviceTokens(userUID);
      const name = getUserDisplayName(followerUID);

      // Notification details.
      const payload = {
        notification: {
          title: 'You have a new follower!',
          body: `${name} is now following you.`
        }
      };
      return admin.messaging().sendToDevice(tokens, payload);
    });

Gửi phản hồi về...

Bạn cần trợ giúp? Truy cập trang hỗ trợ của chúng tôi.