Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Firebase Documentation

Google's backend platform — login, Firestore with live updates, security rules, storage, Cloud Functions and hosting.

Firebase is Google's backend platform: login, a real-time database, file storage, hosting and notifications without running your own server. It suits student projects and mobile apps very well. Examples use the JavaScript SDK; Flutter and Android work the same way.

1. Introduction

Product Does
Authentication Email, Google and phone login
Cloud Firestore NoSQL document database with live updates
Realtime Database Older JSON database
Storage User files and images
Cloud Functions Server code that runs on events
Hosting Serves static sites and SPAs
Cloud Messaging (FCM) Push notifications
Analytics, Crashlytics Usage and crash reports

Pricing: the Spark plan is free with limits. Functions and heavier use need the pay-as-you-go Blaze plan. Set a budget alert.

2. Setup

  1. Create a project at the Firebase console.
  2. Add a web app and copy its config.
  3. Install the SDK:
npm install firebase
// firebase.js
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore';
import { getStorage } from 'firebase/storage';

const app = initializeApp({
  apiKey: '...',
  authDomain: 'my-app.firebaseapp.com',
  projectId: 'my-app',
  storageBucket: 'my-app.appspot.com',
  appId: '...',
});

export const auth = getAuth(app);
export const db = getFirestore(app);
export const storage = getStorage(app);

The web apiKey identifies your project and isn't a secret. Your data is protected by security rules, not by hiding the key.

3. Authentication

import {
  createUserWithEmailAndPassword, signInWithEmailAndPassword, signInWithPopup,
  GoogleAuthProvider, onAuthStateChanged, signOut,
} from 'firebase/auth';
import { auth } from './firebase.js';

await createUserWithEmailAndPassword(auth, email, password);
await signInWithEmailAndPassword(auth, email, password);
await signInWithPopup(auth, new GoogleAuthProvider());
await signOut(auth);

onAuthStateChanged(auth, (user) => {
  if (user) console.log('Logged in:', user.uid);
  else console.log('Logged out');
});

Enable each sign-in method in Authentication → Sign-in method. onAuthStateChanged is the right way to know who's logged in, because login is restored asynchronously after a reload.

4. Firestore Data Model

Firestore stores documents (JSON-like) inside collections.

users (collection)
  └─ uid123 (document)  { name: "Asha", xp: 120 }
       └─ notes (subcollection)
            └─ note1 (document)  { text: "...", createdAt: ... }
  • Documents are limited to 1 MB.
  • Queries are shallow: reading a document doesn't load its subcollections.
  • There are no joins, so copy (denormalise) the data you show together.
  • You pay per read, write and delete.

5. Reading and Writing Data

import {
  collection, doc, addDoc, setDoc, getDoc, getDocs, updateDoc, deleteDoc,
  query, where, orderBy, limit, serverTimestamp, increment,
} from 'firebase/firestore';
import { db } from './firebase.js';

// create
const ref = await addDoc(collection(db, 'notes'), {
  text: 'Hello', uid: user.uid, createdAt: serverTimestamp(),
});
await setDoc(doc(db, 'users', user.uid), { name: 'Asha' }, { merge: true });

// read
const snap = await getDoc(doc(db, 'users', user.uid));
if (snap.exists()) console.log(snap.data());

// query
const q = query(
  collection(db, 'notes'),
  where('uid', '==', user.uid),
  orderBy('createdAt', 'desc'),
  limit(20),
);
const notes = (await getDocs(q)).docs.map((d) => ({ id: d.id, ...d.data() }));

// update and delete
await updateDoc(doc(db, 'users', user.uid), { xp: increment(10) });
await deleteDoc(doc(db, 'notes', ref.id));

Queries that combine filters and sorting need a composite index. The error message gives a link that creates it.

6. Live Updates

import { onSnapshot } from 'firebase/firestore';

const stop = onSnapshot(q, (snap) => {
  const notes = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
  render(notes);
});

stop();    // unsubscribe when the screen closes

In React, subscribe inside useEffect and return stop as the cleanup.

Common mistake: forgetting to unsubscribe leaves listeners running and increases your read count.

7. Security Rules

Rules run on Google's servers and decide who can read and write. Never leave a database open.

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
      allow read: if request.auth != null;
      allow write: if request.auth != null && request.auth.uid == uid;
    }
    match /notes/{id} {
      allow read, update, delete: if request.auth != null && resource.data.uid == request.auth.uid;
      allow create: if request.auth != null
                    && request.resource.data.uid == request.auth.uid
                    && request.resource.data.text is string;
    }
  }
}

resource.data is the stored document, and request.resource.data is the incoming one. Test rules with the Rules Playground and the Emulator Suite.

Common mistake: "test mode" rules allow anyone to read and write, and they expire. Replace them before launch.

8. Storage

import { ref, uploadBytes, getDownloadURL } from 'firebase/storage';
import { storage } from './firebase.js';

const fileRef = ref(storage, `avatars/${user.uid}.jpg`);
await uploadBytes(fileRef, file);
const url = await getDownloadURL(fileRef);

Save url in Firestore. Storage has its own security rules:

match /avatars/{uid}.jpg {
  allow read;
  allow write: if request.auth.uid == uid && request.resource.size < 2 * 1024 * 1024;
}

9. Cloud Functions

Functions run trusted server code: secrets, payments, or actions the client mustn't control.

npm install -g firebase-tools
firebase login
firebase init functions
firebase deploy --only functions
import { onDocumentCreated } from 'firebase-functions/v2/firestore';
import { onCall, HttpsError } from 'firebase-functions/v2/https';

export const welcome = onDocumentCreated('users/{uid}', (event) => {
  console.log('New user', event.params.uid, event.data.data());
});

export const addNumbers = onCall((request) => {
  if (!request.auth) throw new HttpsError('unauthenticated', 'Please log in');
  return { sum: request.data.a + request.data.b };
});

10. Hosting and Notifications

firebase init hosting     # public directory: dist · single-page app: yes
npm run build
firebase deploy --only hosting

FCM sends push notifications: the client gets a token and saves it, and your server or a Function sends messages to it.

import { getMessaging, getToken } from 'firebase/messaging';

const token = await getToken(getMessaging(app), { vapidKey: 'YOUR_KEY' });

11. Firebase vs Your Own Backend

Firebase Own backend (Node + MongoDB)
Start speed Very fast Slower
Server to manage None Yes
Live updates Built in You build them
Complex queries Limited Full
Cost at scale Per operation; can surprise Predictable
Lock-in High Low

Supabase is a popular open-source alternative built on PostgreSQL.

12. Practice Problems

  1. Email and Google login with a protected page.
  2. A notes app on Firestore where users see only their own notes (with rules).
  3. A live chat room with onSnapshot.
  4. Profile photo upload with Storage and a size limit.
  5. A Cloud Function that updates a counter when a post is created.

13. Interview Questions

Firestore vs Realtime Database? Firestore has collections, richer queries and better scaling; Realtime Database is one JSON tree with very low latency.

Is the web API key secret? No. It identifies the project; security rules protect the data.

How do you secure Firestore? With security rules that check request.auth and validate data.

set vs update? set replaces (or merges with merge: true) and creates if missing; update changes fields and fails if the document is missing.

Why denormalise in Firestore? There are no joins, and reads are billed, so data is shaped around how screens read it.

How does onSnapshot work? It keeps a listener open and calls back on every change.

When do you need Cloud Functions? For trusted logic: secrets, payments, or triggers on data changes.

What is serverTimestamp()? A placeholder replaced by Google's server time, so client clocks don't matter.

14. Cheat Sheet & References

Auth

createUserWithEmailAndPassword(auth, email, pass);
signInWithEmailAndPassword(auth, email, pass);
signInWithPopup(auth, new GoogleAuthProvider());
onAuthStateChanged(auth, (user) => {});
signOut(auth);

Firestore

addDoc(collection(db, 'notes'), data);
setDoc(doc(db, 'users', id), data, { merge: true });
getDoc(doc(db, 'users', id));
getDocs(query(col, where('a', '==', 1), orderBy('b'), limit(10)));
updateDoc(ref, { xp: increment(5) });
deleteDoc(ref);
onSnapshot(q, (snap) => {});

Rules

allow read: if request.auth != null;
allow write: if request.auth.uid == uid;
resource.data = stored · request.resource.data = incoming

CLI

firebase login
firebase init
firebase emulators:start
firebase deploy

References