DEV Community

mrcflorian
mrcflorian

Posted on • Updated on

10 Essential Firebase Tutorials for Beginners

In this tutorial, we will explore 10 essential Firebase tutorials for beginners. Firebase is a powerful platform that allows software developers to build and scale their applications quickly. It offers a wide range of features, including authentication, real-time database, cloud firestore, storage, hosting, and deployment. By the end of this tutorial, you will have a solid understanding of Firebase and how to use its various components to build robust web and mobile applications.

essential firebase tutorials for beginners

Introduction

What is Firebase?

Firebase is a Backend-as-a-Service (BaaS) platform that provides developers with a plethora of tools and services to build and scale web and mobile applications. It was initially developed by Firebase Inc. and later acquired by Google in 2014. Firebase offers a comprehensive suite of services, including authentication, real-time database, cloud firestore, storage, hosting, and deployment.

Why use Firebase?

Firebase offers several advantages that make it an excellent choice for developers. Firstly, it eliminates the need for setting up and maintaining your own server infrastructure, allowing you to focus on building your application. Secondly, Firebase provides real-time functionality out of the box, enabling you to build collaborative and interactive applications easily. Lastly, Firebase integrates seamlessly with other Google Cloud services, providing you with a scalable and reliable infrastructure.

Getting started with Firebase

Before diving into the specific tutorials, you need to set up a Firebase project. Follow these steps to get started:

  1. Sign in to the Firebase console using your Google account.
  2. Click on the "Add project" button and provide a name for your project.
  3. Enable the necessary Firebase services based on the tutorials you plan to follow.
  4. Once your project is created, you will be redirected to the project dashboard. Here, you can access various Firebase services and configure them as needed.

Authentication

User registration

User registration is a crucial part of any application. In this tutorial, we will learn how to implement user registration using Firebase Authentication. Here's the code snippet to create a new user:

const email = "example@example.com";
const password = "password123";

firebase.auth().createUserWithEmailAndPassword(email, password)
  .then((userCredential) => {
    // User registration successful
    const user = userCredential.user;
    console.log("User registered:", user.uid);
  })
  .catch((error) => {
    // Handle registration errors
    const errorCode = error.code;
    const errorMessage = error.message;
    console.error("Registration failed:", errorCode, errorMessage);
  });
Enter fullscreen mode Exit fullscreen mode

Let's break down the code:

  1. We define the email and password for the new user.
  2. We call the createUserWithEmailAndPassword method of firebase.auth() to create a new user with the provided email and password.
  3. If the registration is successful, the then block is executed, and we can access the user object from the userCredential.
  4. If an error occurs during registration, the catch block is executed, and we can handle the error accordingly.

User login

User login is another essential feature of an application. In this tutorial, we will learn how to implement user login using Firebase Authentication. Here's the code snippet to log in a user:

const email = "example@example.com";
const password = "password123";

firebase.auth().signInWithEmailAndPassword(email, password)
  .then((userCredential) => {
    // User login successful
    const user = userCredential.user;
    console.log("User logged in:", user.uid);
  })
  .catch((error) => {
    // Handle login errors
    const errorCode = error.code;
    const errorMessage = error.message;
    console.error("Login failed:", errorCode, errorMessage);
  });
Enter fullscreen mode Exit fullscreen mode

Let's analyze the code:

  1. We define the email and password for the user trying to log in.
  2. We call the signInWithEmailAndPassword method of firebase.auth() to authenticate the user using the provided email and password.
  3. If the login is successful, the then block is executed, and we can access the user object from the userCredential.
  4. If an error occurs during login, the catch block is executed, and we can handle the error accordingly.

Social media authentication

Social media authentication allows users to log in using their existing social media accounts. In this tutorial, we will learn how to implement social media authentication using Firebase Authentication. Here's the code snippet to authenticate a user using Google:

const provider = new firebase.auth.GoogleAuthProvider();

firebase.auth().signInWithPopup(provider)
  .then((result) => {
    // User authentication successful
    const user = result.user;
    console.log("User authenticated:", user.uid);
  })
  .catch((error) => {
    // Handle authentication errors
    const errorCode = error.code;
    const errorMessage = error.message;
    console.error("Authentication failed:", errorCode, errorMessage);
  });
Enter fullscreen mode Exit fullscreen mode

Let's break down the code:

  1. We create an instance of the firebase.auth.GoogleAuthProvider class to specify the authentication provider (in this case, Google).
  2. We call the signInWithPopup method of firebase.auth() and pass the provider to initiate the authentication process.
  3. If the authentication is successful, the then block is executed, and we can access the user object from the result.
  4. If an error occurs during authentication, the catch block is executed, and we can handle the error accordingly.

Realtime Database

Creating and updating data

The Realtime Database is a NoSQL cloud-hosted database provided by Firebase. In this tutorial, we will learn how to create and update data in the Realtime Database. Here's an example of creating a new user:

const database = firebase.database();
const usersRef = database.ref("users");

const newUser = {
  name: "John Doe",
  email: "johndoe@example.com"
};

const newUserRef = usersRef.push(newUser);
const userId = newUserRef.key;

console.log("User created with ID:", userId);
Enter fullscreen mode Exit fullscreen mode

Let's analyze the code:

  1. We get a reference to the Realtime Database using firebase.database().
  2. We create a reference to the "users" node in the database using database.ref("users").
  3. We define the data for the new user in the newUser object.
  4. We use the push method on the usersRef to insert the newUser object into the database. This generates a new unique key for the user.
  5. We retrieve the generated key using newUserRef.key and store it in the userId variable.
  6. Finally, we log the user ID to the console.

Reading and querying data

Reading and querying data from the Realtime Database is straightforward using Firebase. In this tutorial, we will learn how to read and query data from the Realtime Database. Here's an example of retrieving a user by their ID:

const database = firebase.database();
const usersRef = database.ref("users");

const userId = "abc123";

usersRef.child(userId).once("value")
  .then((snapshot) => {
    const user = snapshot.val();
    console.log("User retrieved:", user);
  })
  .catch((error) => {
    // Handle read errors
    console.error("Failed to retrieve user:", error);
  });
Enter fullscreen mode Exit fullscreen mode

Let's break down the code:

  1. We get a reference to the Realtime Database using firebase.database().
  2. We create a reference to the "users" node in the database using database.ref("users").
  3. We define the user ID of the user we want to retrieve in the userId variable.
  4. We call the child method on the usersRef and pass the userId to get a reference to the specific user.
  5. We use the once method on the user reference to read the user's data once.
  6. If the read is successful, the then block is executed, and we can access the user data from the snapshot.
  7. If an error occurs during the read operation, the catch block is executed, and we can handle the error accordingly.

Realtime data synchronization

One of the key features of the Realtime Database is its ability to synchronize data in real-time between clients. In this tutorial, we will learn how to sync data in real-time using the Realtime Database. Here's an example of listening for changes in a user's data:

const database = firebase.database();
const usersRef = database.ref("users");

const userId = "abc123";

usersRef.child(userId).on("value", (snapshot) => {
  const user = snapshot.val();
  console.log("Realtime update - User:", user);
});
Enter fullscreen mode Exit fullscreen mode

Let's analyze the code:

  1. We get a reference to the Realtime Database using firebase.database().
  2. We create a reference to the "users" node in the database using database.ref("users").
  3. We define the user ID of the user we want to listen to in the userId variable.
  4. We call the child method on the usersRef and pass the userId to get a reference to the specific user.
  5. We use the on method on the user reference to listen for changes in the user's data.
  6. Whenever a change occurs, the callback function is executed, and we can access the updated user data from the snapshot.

Cloud Firestore

Document-based data model

Cloud Firestore is a flexible, scalable NoSQL document database provided by Firebase. In this tutorial, we will learn about the document-based data model of Cloud Firestore. Here's an example of creating a new document:

const firestore = firebase.firestore();
const usersCollection = firestore.collection("users");

const newUser = {
  name: "John Doe",
  email: "johndoe@example.com"
};

usersCollection.add(newUser)
  .then((docRef) => {
    const userId = docRef.id;
    console.log("User created with ID:", userId);
  })
  .catch((error) => {
    // Handle document creation errors
    console.error("Failed to create user:", error);
  });
Enter fullscreen mode Exit fullscreen mode

Let's break down the code:

  1. We get a reference to Cloud Firestore using firebase.firestore().
  2. We create a reference to the "users" collection in Cloud Firestore using firestore.collection("users").
  3. We define the data for the new user in the newUser object.
  4. We use the add method on the usersCollection to insert the newUser as a new document in the collection.
  5. If the document creation is successful, the then block is executed, and we can access the auto-generated document ID from the docRef.
  6. If an error occurs during document creation, the catch block is executed, and we can handle the error accordingly.

CRUD operations

Cloud Firestore provides powerful CRUD (Create, Read, Update, Delete) operations to manipulate data. In this tutorial, we will learn how to perform CRUD operations in Cloud Firestore. Here's an example of updating a user's document:

const firestore = firebase.firestore();
const usersCollection = firestore.collection("users");

const userId = "abc123";
const updatedData = {
  name: "John Doe Jr.",
  email: "johndoe@example.com"
};

usersCollection.doc(userId).update(updatedData)
  .then(() => {
    console.log("User updated successfully");
  })
  .catch((error) => {
    // Handle update errors
    console.error("Failed to update user:", error);
  });
Enter fullscreen mode Exit fullscreen mode

Let's analyze the code:

  1. We get a reference to Cloud Firestore using firebase.firestore().
  2. We create a reference to the "users" collection in Cloud Firestore using firestore.collection("users").
  3. We define the user ID of the user we want to update in the userId variable.
  4. We define the updated data for the user in the updatedData object.
  5. We call the doc method on the usersCollection and pass the userId to get a reference to the specific user's document.
  6. We use the update method on the document reference to update the user's document with the updatedData.
  7. If the update is successful, the then block is executed.
  8. If an error occurs during the update operation, the catch block is executed, and we can handle the error accordingly.

Realtime updates with Firestore

Similar to the Realtime Database, Cloud Firestore also provides real-time synchronization of data between clients. In this tutorial, we will learn how to listen for real-time updates in Cloud Firestore. Here's an example of listening for changes in a user's document:

const firestore = firebase.firestore();
const usersCollection = firestore.collection("users");

const userId = "abc123";

usersCollection.doc(userId).onSnapshot((snapshot) => {
  const user = snapshot.data();
  console.log("Realtime update - User:", user);
});
Enter fullscreen mode Exit fullscreen mode

Let's break down the code:

  1. We get a reference to Cloud Firestore using firebase.firestore().
  2. We create a reference to the "users" collection in Cloud Firestore using firestore.collection("users").
  3. We define the user ID of the user we want to listen to in the userId variable.
  4. We call the doc method on the usersCollection and pass the userId to get a reference to the specific user's document.
  5. We use the onSnapshot method on the document reference to listen for changes in the document's data.
  6. Whenever a change occurs, the callback function is executed, and we can access the updated user data from the snapshot.

Storage

Uploading and downloading files

Firebase Storage provides a simple and secure way to store and serve user-generated content. In this tutorial, we will learn how to upload and download files using Firebase Storage. Here's an example of uploading a file:

const storage = firebase.storage();
const fileRef = storage.ref("images/profile.jpg");
const file = /* File object */;

fileRef.put(file)
  .then((snapshot) => {
    console.log("File uploaded successfully");
  })
  .catch((error) => {
    // Handle upload errors
    console.error("Failed to upload file:", error);
  });
Enter fullscreen mode Exit fullscreen mode

Let's analyze the code:

  1. We get a reference to Firebase Storage using firebase.storage().
  2. We create a reference to the file we want to upload in Firebase Storage using storage.ref("images/profile.jpg"). Replace the path with the desired location and filename.
  3. We have a file object representing the file to be uploaded. You can obtain this object from an input file element or programmatically.
  4. We use the put method on the fileRef to upload the file to Firebase Storage.
  5. If the upload is successful, the then block is executed.
  6. If an error occurs during the upload, the catch block is executed, and we can handle the error accordingly.

Managing file metadata

Firebase Storage allows you to manage file metadata, such as content type and custom properties. In this tutorial, we will learn how to set and retrieve file metadata using Firebase Storage. Here's an example of setting file metadata:

const storage = firebase.storage();
const fileRef = storage.ref("images/profile.jpg");

const metadata = {
  contentType: "image/jpeg",
  customMetadata: {
    createdBy: "John Doe",
    createdAt: new Date().toString()
  }
};

fileRef.updateMetadata(metadata)
  .then(() => {
    console.log("File metadata updated successfully");
  })
  .catch((error) => {
    // Handle metadata update errors
    console.error("Failed to update file metadata:", error);
  });
Enter fullscreen mode Exit fullscreen mode

Let's break down the code:

  1. We get a reference to Firebase Storage using firebase.storage().
  2. We create a reference to the file for which we want to update metadata using storage.ref("images/profile.jpg"). Replace the path with the actual file location.
  3. We define the metadata for the file in the metadata object. In this example, we set the content type to "image/jpeg" and provide custom metadata properties such as "createdBy" and "createdAt".
  4. We use the updateMetadata method on the fileRef to update the file's metadata with the provided metadata.
  5. If the metadata update is successful, the then block is executed.
  6. If an error occurs during the metadata update, the catch block is executed, and we can handle the error accordingly.

Security rules for storage

Firebase Storage allows you to define security rules to control access to your files. In this tutorial, we will learn how to set security rules for Firebase Storage. Here's an example of setting read and write rules for files:

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read: if true; // Allow read access to all files
      allow write: if request.auth != null; // Allow write access only for authenticated users
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Let's analyze the code:

  1. We define the Firebase Storage security rules within the service firebase.storage block.
  2. We use the match keyword to specify the path pattern to match.
  3. In this example, we use the {bucket} and {allPaths=**} wildcard placeholders to match all files in the storage bucket.
  4. We use the allow keyword to define the permissions for read and write access.
  5. The read rule is set to if true, allowing read access to all files.
  6. The write rule is set to if request.auth != null, allowing write access only for authenticated users.

Hosting and Deployment

Hosting your web app

Firebase Hosting allows you to deploy and host your web applications easily. In this tutorial, we will learn how to host your web app using Firebase Hosting. Here's an example of hosting a web app:

  1. Install the Firebase CLI by running npm install -g firebase-tools in your terminal.
  2. Navigate to your web app's root directory.
  3. Run firebase login to authenticate with your Firebase account.
  4. Run firebase init to set up your Firebase project. Select "Hosting" as the feature to set up and choose the project you created earlier.
  5. Follow the prompts to configure your project. Choose the default options for most of the prompts.
  6. Once the initialization is complete, run firebase deploy to deploy your web app to Firebase Hosting.
  7. After the deployment is successful, you will receive a hosting URL where your web app is accessible.

Deploying Firebase functions

Firebase Functions allows you to run server-side code in response to events triggered by Firebase services. In this tutorial, we will learn how to deploy Firebase Functions. Here's an example of deploying a function:

  1. Navigate to your Firebase project's root directory.
  2. Open the terminal and run firebase deploy --only functions to deploy only the functions in your project.
  3. Firebase will upload your functions to the cloud and provide you with the deployment URLs and other relevant information.

Custom domain setup

Firebase Hosting allows you to set up a custom domain for your web app. In this tutorial, we will learn how to set up a custom domain using Firebase Hosting. Here's an example of setting up a custom domain:

  1. Open the Firebase console and navigate to your project.
  2. Go to the "Hosting" section and click on the "Add custom domain" button.
  3. Enter your custom domain and click "Continue".
  4. Follow the instructions provided by Firebase to verify domain ownership and configure DNS settings.
  5. Once the domain is verified and DNS settings are propagated, your web app will be accessible using the custom domain.

Conclusion

In this tutorial, we explored 10 essential Firebase tutorials for beginners. We covered various aspects of Firebase, including authentication, real-time database, Cloud Firestore, storage, hosting, and deployment. By following these tutorials, you should now have a solid understanding of Firebase and how to use its different components to build powerful web and mobile applications. Firebase is a versatile platform that can greatly simplify the development process and empower you to build scalable and robust applications. Experiment with the code examples provided and continue exploring the Firebase documentation or other source codes (such as this React Native Ecommerce App ) to expand your knowledge further. Happy coding!

Top comments (0)