logo
eng-flag

Firebase Cheatsheet

Table of Contents

  1. Firebase Authentication
  2. Firebase Realtime Database
  3. Cloud Firestore
  4. Firebase Cloud Storage
  5. Firebase Cloud Functions
  6. Firebase Hosting
  7. Firebase Cloud Messaging
  8. Firebase Analytics
  9. Firebase Performance Monitoring
  10. Firebase Remote Config

Firebase Authentication

Initialize Firebase Auth

const auth = firebase.auth();

Sign Up with Email and Password

auth.createUserWithEmailAndPassword(email, password)
  .then((userCredential) => {
    // Signed in 
    const user = userCredential.user;
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
  });

Sign In with Email and Password

auth.signInWithEmailAndPassword(email, password)
  .then((userCredential) => {
    // Signed in
    const user = userCredential.user;
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
  });

Sign Out

auth.signOut().then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});

Get Current User

const user = auth.currentUser;

Listen for Auth State Changes

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

Firebase Realtime Database

Initialize Realtime Database

const database = firebase.database();

Write Data

database.ref('users/' + userId).set({
  username: name,
  email: email,
  profile_picture : imageUrl
});

Read Data Once

database.ref('/users/' + userId).once('value').then((snapshot) => {
  const username = (snapshot.val() && snapshot.val().username) || 'Anonymous';
});

Listen for Changes

database.ref('/users/' + userId).on('value', (snapshot) => {
  const data = snapshot.val();
  updateStarCount(postElement, data);
});

Update Data

database.ref('users/' + userId).update({
  username: newUsername
});

Remove Data

database.ref('users/' + userId).remove();

Cloud Firestore

Initialize Cloud Firestore

const db = firebase.firestore();

Add a Document

db.collection("users").add({
    first: "Ada",
    last: "Lovelace",
    born: 1815
})
.then((docRef) => {
    console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
    console.error("Error adding document: ", error);
});

Set a Document

db.collection("cities").doc("LA").set({
    name: "Los Angeles",
    state: "CA",
    country: "USA"
});

Get a Document

db.collection("cities").doc("LA")
    .get().then((doc) => {
        if (doc.exists) {
            console.log("Document data:", doc.data());
        } else {
            console.log("No such document!");
        }
    }).catch((error) => {
        console.log("Error getting document:", error);
    });

Real-time Updates

db.collection("cities").doc("LA")
    .onSnapshot((doc) => {
        console.log("Current data: ", doc.data());
    });

Query Documents

db.collection("cities").where("capital", "==", true)
    .get()
    .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            console.log(doc.id, " => ", doc.data());
        });
    });

Firebase Cloud Storage

Initialize Cloud Storage

const storage = firebase.storage();

Upload a File

const ref = storage.ref('images/mountains.jpg');
const file = ... // Use a Blob or File API to get the file

ref.put(file).then((snapshot) => {
  console.log('Uploaded a file!');
});

Download a File URL

storage.ref('images/mountains.jpg').getDownloadURL()
  .then((url) => {
    // Insert url into an <img> tag to "download"
  });

Delete a File

const ref = storage.ref('images/mountains.jpg');
ref.delete().then(() => {
  // File deleted successfully
}).catch((error) => {
  // An error occurred!
});

Firebase Cloud Functions

Initialize Cloud Functions (in your Firebase project)

const functions = require('firebase-functions');

HTTP Function

exports.helloWorld = functions.https.onRequest((request, response) => {
  response.send("Hello from Firebase!");
});

Firestore Trigger

exports.createUser = functions.firestore
    .document('users/{userId}')
    .onCreate((snap, context) => {
      // Get an object representing the document
      const newValue = snap.data();
      
      // access a particular field as you would any JS property
      const name = newValue.name;

      // perform desired operations ...
    });

Firebase Hosting

Initialize Firebase Hosting

firebase init hosting

Deploy to Firebase Hosting

firebase deploy --only hosting

Firebase Cloud Messaging

Initialize Cloud Messaging

const messaging = firebase.messaging();

Request Permission

messaging.requestPermission()
.then(() => {
  console.log('Notification permission granted.');
  return messaging.getToken();
})
.then((token) => {
  console.log('Token:', token);
})
.catch((err) => {
  console.log('Unable to get permission to notify.', err);
});

Handle Incoming Messages

messaging.onMessage((payload) => {
  console.log('Message received. ', payload);
});

Firebase Analytics

Initialize Analytics

const analytics = firebase.analytics();

Log an Event

analytics.logEvent('select_content', {
  content_type: 'image',
  content_id: 'P12453'
});

Set User Properties

analytics.setUserProperties({favorite_food: 'pizza'});

Firebase Performance Monitoring

Initialize Performance Monitoring

const perf = firebase.performance();

Start a Trace

const trace = perf.trace('test_trace');
trace.start();

// Do some time-consuming work...

trace.stop();

Firebase Remote Config

Initialize Remote Config

const remoteConfig = firebase.remoteConfig();

Fetch and Activate Values

remoteConfig.fetchAndActivate()
  .then(() => {
    const welcomeMessage = remoteConfig.getValue('welcome_message');
    console.log(welcomeMessage.asString());
  })
  .catch((err) => {
    console.error('Error fetching remote config.', err);
  });

2024 © All rights reserved - buraxta.com