Skip to content
Tutorials Center
My learning

Topics

Lesson 83 of 132 ยท Routing and Apps

Firebase with React: Auth and Firestore

Use Firebase from React - initialize the SDK, build an auth-state hook, read and write Firestore with live listeners, clean up subscriptions, and understand security rules - with runnable stand-ins.

Firebase is Google's backend-as-a-service: it gives a front-end developer authentication, a cloud database (Firestore), file storage and hosting without writing a server. For React apps it is a popular way to get a working back end in an afternoon. This lesson shows how the pieces fit into React: initializing the SDK, turning "who is signed in" into a hook, reading and writing Firestore with live updates, and the one security idea you must not skip.

Firebase needs a real project, API keys and a network, so none of the SDK code can run in the editor. The Firebase snippets are read-only and written against the modular SDK (version 9 and later, with import { ... } from 'firebase/...'). Every concept has a runnable stand-in: a tiny fake auth and db in memory with the same shape (subscribe, write, unsubscribe), so you can practice the React side. The stand-ins are not Firebase.

Setting up

Terminal
npm install firebase

Create a project in the Firebase console, add a web app, and copy its configuration object into a module that initializes the SDK once:

JavaScript
// firebase.js (read-only)
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore';

const app = initializeApp({
  apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
  authDomain: 'my-app.firebaseapp.com',
  projectId: 'my-app',
  appId: '1:123:web:abc',
});

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

A common worry: these values are visible in the browser. That is expected. A Firebase web config is an identifier, not a secret. What protects your data is security rules (below) and, for sign-in, the list of authorized domains in the console. Never put server credentials (service-account keys) in front-end code.

Authentication state as a hook

Firebase Auth keeps the session for you (the user stays signed in after a reload) and tells you about changes through onAuthStateChanged. This is a textbook case for a custom hook over an external subscription, with a cleanup:

JSX
// useAuth.js (read-only)
import { useEffect, useState } from 'react';
import { onAuthStateChanged } from 'firebase/auth';
import { auth } from './firebase';

export function useAuth() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // onAuthStateChanged returns an unsubscribe function: use it as the cleanup
    return onAuthStateChanged(auth, (nextUser) => {
      setUser(nextUser);
      setLoading(false);
    });
  }, []);

  return { user, loading };
}

The loading flag matters: on first render Firebase has not yet restored the saved session, so user is null for a moment even for a signed-in person. If you treat that as "signed out" you will flash the login screen and redirect people away. Render a spinner until loading is false.

Signing in and out are plain async functions:

JSX
// read-only
import { signInWithEmailAndPassword, createUserWithEmailAndPassword, signOut,
         GoogleAuthProvider, signInWithPopup } from 'firebase/auth';

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

Errors have a code such as auth/invalid-credential or auth/email-already-in-use; map those to friendly messages and do not show raw codes. Share the user through context so any component can read it and protect routes, as in Authentication patterns.

Firestore in one minute

Firestore stores documents (JSON-like objects) inside collections. A document lives at a path such as todos/abc123, may contain nested data and even sub-collections, and has no fixed schema. Reads and writes are async; reads can be one-off (getDocs) or live (onSnapshot).

JSX
// read-only
import { collection, addDoc, deleteDoc, doc, updateDoc, query, where, orderBy,
         onSnapshot, serverTimestamp } from 'firebase/firestore';

// Create
await addDoc(collection(db, 'todos'), { text, uid: user.uid, done: false, createdAt: serverTimestamp() });

// Update and delete one document
await updateDoc(doc(db, 'todos', id), { done: true });
await deleteDoc(doc(db, 'todos', id));

// Live query: runs the callback now and on every change
const q = query(collection(db, 'todos'), where('uid', '==', user.uid), orderBy('createdAt', 'desc'));
const unsubscribe = onSnapshot(q, (snapshot) => {
  const todos = snapshot.docs.map((d) => ({ id: d.id, ...d.data() }));
  // set state with todos
});

Queries that combine where and orderBy on different fields need a composite index; the error message in the console contains a link that creates it.

A live collection as a hook

Wrapping onSnapshot gives you data that updates itself, with the unsubscribe in the cleanup so listeners do not leak:

JSX
// useTodos.js (read-only)
export function useTodos(uid) {
  const [todos, setTodos] = useState([]);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!uid) { setTodos([]); return; }
    const q = query(collection(db, 'todos'), where('uid', '==', uid), orderBy('createdAt', 'desc'));
    return onSnapshot(
      q,
      (snapshot) => setTodos(snapshot.docs.map((d) => ({ id: d.id, ...d.data() }))),
      (err) => setError(err)               // permission denied shows up here
    );
  }, [uid]);

  return { todos, error };
}

Because the listener pushes changes to you, writes do not need to update local state by hand: you call addDoc, Firestore applies the write locally at once (so the UI is instant), notifies your listener, and later confirms with the server.

A runnable stand-in

Below, a fake auth and db mimic the same API shapes: onAuthStateChanged returns an unsubscribe, the "database" notifies listeners after every write, and the hooks useAuth and useTodos have the same structure as the real ones. Sign in as Ada or Linus, add todos, and notice that each person sees only their own.

Stand-in: useAuth and a live todos hook over a fake Firebase

Notice the first second: "Restoring session..." appears before the sign-in buttons, which is the loading flag at work. Sign in as Ada, add a todo, sign out, sign in as Linus: Linus's list starts empty. In the stand-in that separation is just a filter in code. In real Firebase a filter in your query is not security: anyone can open the browser console and query the whole collection. Security belongs in rules.

Security rules

Firestore and Storage are protected by security rules that run on Google's servers for every read and write. Without them (or with the "test mode" rules that open everything for 30 days) your database is public. A rule that lets users touch only their own todos:

Text
// firestore.rules (read-only)
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /todos/{todoId} {
      allow read, update, delete: if request.auth != null && request.auth.uid == resource.data.uid;
      allow create: if request.auth != null
                    && request.resource.data.uid == request.auth.uid
                    && request.resource.data.text is string
                    && request.resource.data.text.size() < 500;
    }
  }
}

Test rules with the Firebase emulator before shipping. Remember: the client is untrusted. Validation in React is for convenience; the rules (or a trusted backend) are the authority. The same thinking applies to React security.

Storage

Firebase Storage holds files such as avatars. You upload with uploadBytes (or uploadBytesResumable for progress), then ask for the public address with getDownloadURL:

JSX
// read-only
import { getStorage, ref, uploadBytes, getDownloadURL } from 'firebase/storage';

async function uploadAvatar(file, uid) {
  const fileRef = ref(getStorage(), `avatars/${uid}.jpg`);
  await uploadBytes(fileRef, file);
  return getDownloadURL(fileRef);
}

Storage has its own rules; limit size and content type there. See file forms for the input side of an upload.

Common mistakes

  • Treating user === null as "signed out" before the first auth callback. Track loading.
  • Forgetting to unsubscribe from onAuthStateChanged and onSnapshot. The cleanup of the effect must call the returned function, or listeners pile up and cost reads.
  • Relying on client-side filters for privacy. Use rules.
  • Leaving test-mode rules in place.
  • Reading too much. Firestore bills per document read, and a live listener on a large collection re-reads on changes; query only what you show, and paginate with limit.
  • Calling initializeApp more than once, for example in a component. Put it in one module.
  • Storing dates as strings. Use serverTimestamp() or Timestamp, so sorting works.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a useAuth hook usually need a loading flag?

    Without the flag you would show the login screen or redirect for a moment, even when the user is signed in. Wait for the first onAuthStateChanged callback.
  2. 2. What does onSnapshot return, and what should you do with it?

    Live listeners stay active until unsubscribed. Returning the unsubscribe function from the effect stops the listener when the component unmounts or dependencies change.
  3. 3. Is it a problem that the Firebase web config (apiKey, projectId) is visible in the browser?

    The web config is not a secret. Real protection comes from security rules. Service-account keys, by contrast, must never be in front-end code.
  4. 4. Why is filtering with where('uid', '==', user.uid) in the client not enough to protect data?

    The client is untrusted. Rules decide who may read or write, regardless of what your React code asks for.
  5. 5. What is a document in Firestore?

    Firestore is a document database: collections hold documents, which can contain nested data and sub-collections, without a fixed schema.

Summary

  • Initialize Firebase once in a module and export auth and db; the web config is an identifier, not a secret.
  • onAuthStateChanged and onSnapshot return unsubscribe functions: return them from useEffect for clean subscriptions.
  • A useAuth hook needs a loading state; share the user through context.
  • Firestore stores documents in collections; use addDoc, updateDoc, deleteDoc, query and live listeners.
  • Security rules, not client code, protect data; never ship test-mode rules.
  • Keep server credentials out of the front end.

Next: Server Components