Firebase is a platform for running and managing apps on the cloud. It’s a fully-featured “backend as a service” (BaaS) that scales automatically to millions of users. It offers tons of features for development (authentication, database, storage, messaging), user engagement (insights, experimentation, customization), and operations (testing, troubleshooting of stability and performance, feature rollout, and adoption monitoring). You just focus on writing your awesome app and let Firebase manage the infrastructure and much of the tedious operational concerns.
Firebase is part of Google Cloud.
Make sure to get familiar with:
As of October, 2022, Firebase provides these 18 products:
Currently the Firebase documentation groups the products into three main areas:
Group | Products |
---|---|
Build | Authentication • Cloud Firestore • Storage • Hosting • Cloud Functions • Machine Learning • Realtime Database • App Check |
Release & Monitor | App Distribution • Crashlytics • Performance Monitoring • Test Lab |
Engage | Analytics • Cloud Messaging • Remote Config • A/B Testing • Dynamic Links • In-App Messaging |
There are additional sections in the documentation not tied to any of the main products, but are good to know about:
The documentation also shows how to link other Google products into your Firebase app, such as Google AdMob and Google Ads.
When developing and managing your project, you use either or both of:
In your app itself, you access Firebase services through either or both of:
The general idea with Firebase is to first create a project (generally you will do this on the Firebase Console) then in your code enable and use just the services you need. For example, in web apps, your initialization code will look something like:
import { initializeApp } from 'firebase/app'; import { getFirestore, /* and maybe other things */ } from 'firebase/firestore'; import { getAuth, /* and maybe other things */ } from 'firebase/auth'; // ... and do the same for other services you need const app = initializeApp({ /* Your config */ }); const db = getFirestore(app); const auth = getAuth(app); // ... and do the same for other services you need
There is complete documentation for Firebase setup on:
And if you are using Firebase form a server, check the docs for how to get set up with the Admin SDK.
Before we get to our code along, a word about security!
Firebase is part of the Google Cloud, so if you are connecting to Firebase services from a server, or the console, your authentication and authorization will be configured through Google Cloud’s IAM.
But what about that SDK for the web client?, How can a web client talk to...a database 😬? The answer is: security rules. You configure rules that will examine all requests from a client—the same kinds of rules you would put in a server that your write yourself. (These security rules apply only to client SDKs; server, console, and API access use IAM instead).
It’s a good idea to learn everything you can about security rules, both in terms on the general approach and the specifics for different products:
So, yup, if a web client is talking directly for Firebase, there is no way to hide your database credentials at all, and you must rely on the security rules to prevent all the bad things. You can “do a little more” beyond the security rules, for example, you can:
There are some articles with security tips floating around the web, including How to Keep Your Firebase Project Safe and Secure from everyone.
If you have a Google account and are logged in, you can go directly to your Firebase Console and start exploring. Maybe look at the overview page of the docs and follow links to various guides, code labs and tutorials, quick starts, and samples. The Fundamentals page is a good one.
After browsing the guides, reading about the fundamentals, doing a quick start or code lab, and maybe watching some introductory videos, you will be ready to create a Firebase project of your own from scratch.
Two PlaylistsThe Net Ninja has a playlist on developing web apps with Firebase, using Vanilla JS. For a playlist that uses React, but fewer Firebase features, try this one from Logicism.
Or want to learn from these notes? Let’s do a code-along!
Let's build a blog web application using React with Firebase Authentication and Firestore.
useState
and useEffect
.npm install
and npm start
in the VS Code terminal, as you would for any create-react-app (CRA) application.. ├── README.md ├── package.json ├── package-lock.json ├── public │ ├── index.html │ ├── favicon.ico │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt └── src ├── index.js ├── index.css ├── components │ ├── App.js │ ├── App.css │ ├── App.test.js │ ├── Article.js │ ├── ArticleEntry.js │ └── Nav.js ├── services │ └── articleService.js ├── reportWebVitals.js └── setupTests.js
</>
).npm install firebase
on the command line in your project folder.npm install -g firebase-tools
. You can do this now or even wait until later. It is also possible that you’ve already done it.import { initializeApp } from "firebase/app" import { getAuth } from "firebase/auth" import { getFirestore } from "firebase/firestore" const firebaseConfig = { // THE CONFIG FROM YOUR FIREBASE CONSOLE } export const app = initializeApp(firebaseConfig) export const auth = getAuth(app) export const db = getFirestore(app)
import { useState, useEffect } from "react" import { signInWithPopup, GoogleAuthProvider, signOut } from "firebase/auth" import { auth } from "../firebaseConfig" export function SignIn() { return <button onClick={() => signInWithPopup(auth, new GoogleAuthProvider())}>Sign In</button> } export function SignOut() { return ( <div> Hello, {auth.currentUser.displayName} <button onClick={() => signOut(auth)}>Sign Out</button> </div> ) } export function useAuthentication() { const [user, setUser] = useState(null) useEffect(() => { return auth.onAuthStateChanged((user) => { user ? setUser(user) : setUser(null) }) }, []) return user }
import { useEffect, useState } from "react" import Nav from "./Nav" import Article from "./Article" import ArticleEntry from "./ArticleEntry" import { SignIn, SignOut, useAuthentication } from "../services/authService" import { fetchArticles, createArticle } from "../services/articleService" import "./App.css" export default function App() { const [articles, setArticles] = useState([]) const [article, setArticle] = useState(null) const [writing, setWriting] = useState(false) const user = useAuthentication() // This is a trivial app, so just fetch all the articles only when // a user logs in. A real app would do pagination. Note that // "fetchArticles" is what gets the articles from the service and // then "setArticles" writes them into the React state. useEffect(() => { if (user) { fetchArticles().then(setArticles) } }, [user]) // Update the "database" *then* update the internal React state. These // two steps are definitely necessary. function addArticle({ title, body }) { createArticle({ title, body }).then((article) => { setArticle(article) setArticles([article, ...articles]) setWriting(false) }) } return ( <div className="App"> <header> Blog {user && <button onClick={() => setWriting(true)}>New Article</button>} {!user ? <SignIn /> : <SignOut />} </header> {!user ? "" : <Nav articles={articles} setArticle={setArticle} />} {!user ? ( "" ) : writing ? ( <ArticleEntry addArticle={addArticle} /> ) : ( <Article article={article} /> )} </div> ) }
articles
. Each document should have fields title
(of type string), body
(of type string), and date
(of type timestamp). Let Firebase choose the ids.// This service completely hides the data store from the rest of the app. // No other part of the app knows how the data is stored. If anyone wants // to read or write data, they have to go through this service. import { db } from "../firebaseConfig" import { collection, query, getDocs, addDoc, orderBy, limit, Timestamp } from "firebase/firestore" export async function createArticle({ title, body }) { const data = { title, body, date: Timestamp.now() } const docRef = await addDoc(collection(db, "articles"), data) return { id: docRef.id, ...data } } // NOT FINISHED: This only gets the first 20 articles. In a real app, // you implement pagination. export async function fetchArticles() { const snapshot = await getDocs( query(collection(db, "articles"), orderBy("date", "desc"), limit(20)) ) return snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data(), })) }
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow write: if request.auth.uid == '****************************'; allow read: if request.auth != null; } } }substituting your Google user id for the asterisk sequence. This way only you can write to the Firestore but anyone can read as long as they are logged in. (You can find your uid on the Auth part of the console if you enabled Google sign-in and you added yourself as the user.)
$ npm run build
$ npm install -g firebase-tools(On some machines you might have to prefix the command with
sudo
.)$ firebase --version 11.15.0
$ firebase login
so that you are authenticated for all subsequent commands (it would be sad if Google didn’t check this, right?)
$ firebase init
When asked to select features, just choose hosting, since auth and firestore were already selected in the console. For the other questions: Select your existing project, and choose build when asked about your project’s public directory.
$ firebase deploy
Let’s try out the app in class and look for things to improve. Sure CSS is one thing. But there are likely many other things that should be worked on. Let’s see what we can come up with.
Some initial ideas:
A few things come to mind:
(This list is not exhaustive.)
firebase deploy
(since you have already logged in and initialized the project).