100 Firebase Tips, Tricks, and Screw-ups

FireshipFireship
Science & Technology6 min read25 min video
Oct 14, 2019|202,294 views|7,773|265
Save to Pod

Key Moments

TL;DR

Firebase tips: Project setup, deployment, databases, auth, data modeling, security, storage, functions, and ML.

Key Insights

1

Use separate Firebase projects for development and production.

2

Optimize web app deployments with Firebase Hosting rewrites and custom domains.

3

Choose between Cloud Firestore and Realtime Database based on query needs and write frequency.

4

Secure your Firebase data with robust security rules and the Firestore emulator.

5

Leverage Firebase Storage for assets and implement efficient upload/download strategies.

6

Write idempotent, optimized, and well-tested Cloud Functions for backend logic.

7

Enhance user experience with Firebase Analytics, Cloud Messaging, and ML Kit features.

PROJECT SETUP AND DEPLOYMENT STRATEGIES

For any serious application, establish distinct Firebase projects for development and production to maintain a safe testing sandbox and protect customer data. Integrate Google Analytics for automatic tracking across platforms. In team environments, diligently manage user permissions via the Settings tab, adhering to the principle of least privilege. Always update data privacy information for GDPR compliance. When adding new apps, understand that the provided credentials are safe in front-end code if security rules are properly configured. To manage costs effectively, upgrade to the Blaze plan (pay-as-you-go) and set up budget alerts in the GCP console to monitor usage and identify cost-heavy services.

FIREBASE HOSTING AND WEB APPLICATIONS

Install the Firebase CLI globally and use NPM scripts for web app deployment. Specify different projects for development and production deployments using the project flag. Firebase Hosting offers a default domain but also supports custom domains for multiple sites within a single project, configured via an array in `firebase.json`. Flexibly rewrite traffic to Cloud Functions or Cloud Run for server-side rendering (SSR) with frameworks like Next.js. Dynamic link rewrites can optimize user experience by directing them to the most relevant app screen. Customize cache behavior and security headers for static files, and integrate with Google Cloud Build for automated deployments upon Git commits.

DATABASE SELECTION AND DATA MANAGEMENT

Cloud Firestore is generally preferred for its advanced query capabilities and lower storage costs compared to Realtime Database, which excels in scenarios with high write frequency due to its lack of write charges. While Firebase is cost-effective, set up regular data backups to a dedicated Cloud Storage bucket. Begin with databases in 'locked mode' and incrementally allow operations for enhanced security. Firestore's console allows direct querying and code generation. For JavaScript, import services individually from the `firebase/app` namespace to avoid large bundles, employing progressive enhancement. Frameworks like Angular Fire and React Fire offer seamless integration.

AUTHENTICATION AND DATA MODELING IN FIRESTORE

Implement robust authentication by establishing listeners for auth state changes or fetching the current user on demand. Handle authentication errors gracefully by routing them to user-facing UI elements. Utilize lazy user registration, starting with anonymous sign-ins before collecting further details. For custom email actions like verification or password resets, implement custom email action handlers or even a private SMTP server. Model relationships effectively: use document IDs for one-to-one, subcollections for one-to-many, and embedded maps or arrays for many-to-many. Employ `collectionGroup` queries for cross-user data and `arrayUnion`/`arrayRemove` for array manipulation.

OFFLINE SUPPORT, TIMESTAMPS, AND ATOMIC OPERATIONS

Firestore offers seamless offline support, queuing writes locally and syncing when connectivity returns, with `synchronizeTabs` enabling cross-tab synchronization. Use `serverTimestamp` for accurate timestamps instead of client-side values. Increment counters atomically using `increment` FieldValue. For high-volume writes to a single document, implement distributed counters using Firebase extensions. Ensure operations that must succeed or fail together are grouped using batch writes, maintaining data integrity. For complex relational needs beyond NoSQL, consider integrating with MySQL or using Algolia for full-text search.

SECURITY RULES AND FIRESTORE SIMULATION

Deploying without robust security rules is a major risk; always simulate and test them using the Firestore emulator. Security rules evaluate `request` (authentication, incoming data) and `resource` (existing data). Define fine-grained rules for `get`, `query`, `create`, `update`, and `delete` operations, or combine them using `read` and `write`. Use the `get()` function to reference other documents for rule evaluation, mindful of the read cost. Refactor repetitive logic into functions like `isAdmin` for cleaner rulesets. Remember that rules are evaluated on a per-document basis.

CLOUD STORAGE AND ASSET MANAGEMENT

Utilize Cloud Storage for assets like images and videos, with a default bucket for user content and the option for additional buckets (e.g., for backups, utilizing cold line storage for cost savings). Save both the storage location and download URL in Firestore for easy access and future manipulation. Use `storageRef.fromURL()` to access files via URL or path. List directory contents with `listAll()` and upload files by creating a reference and using the `put()` method. Monitor upload progress via `state_changed` events. Firebase extensions, like the image resizer, automate common tasks such as resizing images for different devices.

FIREBASE ADMIN SDK AND LOCAL DEVELOPMENT

The Firebase Admin SDK enables backend operations. Install it as a dev dependency in Node.js projects and initialize it with service account credentials. Securely manage service accounts using environment variables (`GOOGLE_APPLICATION_CREDENTIALS`) locally, and ensure they are excluded from version control. Seed databases with dummy data using libraries like Faker.js, running scripts from the command line. Explore the Admin SDK's REST APIs for advanced features and automation, such as setting up cron jobs for database backups via the Google API NPM package.

CLOUD FUNCTIONS BEST PRACTICES

Develop Cloud Functions using TypeScript for robust setup and error catching. Minimize dependencies to improve cold start times and reduce CPU usage. Utilize global variables for reusable values across function invocations. Designing idempotent functions is crucial, as they can be invoked multiple times; use `context.eventId` to ensure uniqueness. Scale functions by increasing memory and timeout limits using `runWith()`. Avoid infinite loops, especially when updating triggering documents, by checking document equality before and after operations. Background functions must return promises, achievable with `async/await`.

ADVANCED CLOUD FUNCTION TRIGGERS AND DEPLOYMENT

For inter-service communication, prefer Pub/Sub functions over HTTP functions for enhanced security and simplicity. Secure endpoints by using callable functions, which inherently include user authentication context, simplifying both front-end and back-end code. Callable functions are ideal for sensitive backend operations like deleting entire Firestore collections, implemented recursively with batching to manage large datasets efficiently and prevent memory issues. Break down backend logic into small, reusable JavaScript functions for better testability and code sharing across multiple functions.

CLOUD FUNCTIONS TESTING AND MONITORING

Test Cloud Functions thoroughly using the Cloud Functions Shell locally, invoking them with mock data. Utilize Firebase's unit testing library for automated verification. Monitor production functions for errors in Firebase logs or invest in Stackdriver for custom dashboards, alerts, and proactive issue identification. Deploying functions can be done individually by appending the function name to the deploy command, which is particularly useful for large projects with numerous functions.

ENHANCING USER EXPERIENCE WITH ANALYTICS AND ML

Track custom events and user properties in Firebase Analytics to understand user behavior and identify conversion drivers. Create targeted audiences for marketing campaigns, A/B testing, and funnels. Use analytics data to dynamically customize the UI based on user segments or properties. Leverage Firebase Cloud Messaging to send segmented push notifications, increasing relevance and engagement. Integrate machine learning features through Predictions (purchase likelihood), ML Kit (object detection, smart reply), or AutoML for custom model training using exported data to BigQuery.

Common Questions

Using separate Firebase projects for development and production provides a safe sandbox for testing and experimentation, ensuring that your live customer data remains pristine.

Topics

Mentioned in this video

softwareGoogle Cloud SDK

This SDK provides access to the g-cloud command, which is necessary for managing Google Cloud Platform projects, including Firebase projects.

softwareFirebase App Distribution

This service allows distributing iOS and Android apps to testers, bypassing TestFlight and the Google Play Store.

softwareNPM

A package manager often used in web development to install tools like Firebase CLI.

softwareFirestore Emulator

A tool for local development that simulates the Firestore database, allowing extensive testing of security rules.

softwareGoogle Analytics

Firebase can automatically set up Google Analytics for iOS, Android, and web applications, providing insights into user behavior.

softwareFirebase Command Line Tools

These tools need to be installed globally on a system to interact with Firebase projects from the command line.

softwareCloud Storage

A service within Firebase used for storing large objects like images, videos, and other files, with options for different storage classes like Coldline for backups.

softwareReact Fire

A library for React applications that provides support for hooks and suspense.

softwareFirestore

The primary NoSQL database discussed, used for managing relational data with techniques like subcollections and collection groups.

conceptcollection group

A Firestore query method that allows grouping and querying subcollections with the same name across different parent documents.

conceptBlaze

The Blaze plan is a pay-as-you-go option for Firebase that still includes free features, but requires cost monitoring.

softwareCloud Firestore

A NoSQL database offered by Firebase with powerful query capabilities and lower cost per gigabyte stored compared to Realtime Database.

softwarePub/Sub

A messaging service that can be used to set up Pub/Sub functions for secure communication between internal services, serving as an alternative to HTTP functions.

softwareGoogle Cloud Build

Can be integrated with Firebase Hosting to automatically deploy new site versions on every Git commit.

conceptCallable Functions

A type of Firebase Cloud Function that simplifies backend and frontend code by including authentication context, eliminating the need for manual token verification.

conceptGDPR

Users should update their contact information in the data privacy tab to ensure compliance with GDPR regulations.

conceptcallbacks

A programming technique, often used with functional programming, that is useful for listening to asynchronous events like authentication state changes.

softwareRx Fire

A library for integrating RxJS with frameworks like Svelte, working well with Firebase.

softwareFlutter

A UI toolkit for building natively compiled applications for mobile, web, and desktop from a single codebase, with Firebase support.

softwarePerformance Monitoring

A Firebase service that helps track app performance by providing metrics like first contentful paint across devices.

softwareAutoML

A service that allows building custom image classification models within Firebase.

softwareAngular Universal

A framework that can be used with Firebase Hosting rewrites for Server-Side Rendering (SSR).

softwareAngular Fire

A library for Angular applications that integrates Firebase with change detection and the Angular router.

conceptasync/await

An asynchronous programming pattern useful in JavaScript for handling operations like fetching user data.

softwareStackdriver

A platform for creating custom dashboards and alerts for monitoring application performance and issues, an alternative to Firebase logs.

conceptA/B testing

A marketing technique that can be performed using Firebase Analytics audiences to compare different versions of messaging or UI elements.

softwareGCP Console

The Google Cloud Platform console should be used to set up budget alerts and monitor monthly usage for Firebase projects.

conceptUTF-8

A character encoding standard that allows emojis to be used and queried within Firestore documents as regular strings.

softwareFirebase Extensions

Pre-built solutions that can be used to add functionality to Firebase projects, such as distributed counters or image resizing.

softwareRealtime Database

A NoSQL database by Firebase that does not charge for writes, making it suitable for frequently updated data like IoT sensors.

softwareCrashlytics

A Firebase service for native mobile apps that provides error and crash reporting, automatically opening issues for developers.

softwareML Kit

A Firebase service that allows the implementation of AI-driven features out-of-the-box, such as object detection and smart reply.

softwareFirebase Analytics

Provides default reporting from Google Analytics with a single line of code to gain insights into user behavior.

softwareCloud Functions Shell

A local tool for testing Cloud Functions by invoking them with mock data, crucial for preventing production bugs.

softwareBigQuery

A data warehouse that Firebase Analytics and Firestore data can be exported to, enabling training of custom TensorFlow models.

bookFast and the Furious

An example used to illustrate wildcard string matching in Firestore queries, matching titles that start with the given phrase.

softwareAlgolia

A service for full-text search that can be integrated with Firebase projects.

toolMySQL
toolFaker.js
toolTwitter
toolArduino
toolTensorFlow

More from Fireship

View all 16 summaries

Found this useful? Build your knowledge library

Get AI-powered summaries of any YouTube video, podcast, or article in seconds. Save them to your personal pods and access them anytime.

Try Summify free