Uses of Firebase

User
What is the use of firebase
Assistant
Firebase is a **backend-as-a-service (BaaS)** platform developed by Google that helps developers build, improve, and scale web and mobile applications. It provides a suite of tools and services for backend development, eliminating the need for managing servers manually.

### **Key Uses of Firebase**
1. **Real-time Database & Firestore**
– Stores and syncs data in real-time across all connected clients.
– Firestore provides a NoSQL cloud database with scalability.

2. **Authentication**
– Provides authentication methods including Email/Password, Google, Facebook, Twitter, and more.
– Supports OAuth and custom authentication.

3. **Cloud Storage**
– Stores user-generated content like images, videos, and documents.
– Offers scalable and secure storage with Google Cloud integration.

4. **Cloud Functions**
– Allows running server-side logic in response to database changes, user actions, or HTTP requests.
– Functions as a serverless backend.

5. **Hosting**
– Provides fast and secure web hosting with a global CDN.
– Ideal for hosting static websites, SPAs, and Progressive Web Apps (PWAs).

6. **Cloud Messaging (FCM)**
– Enables push notifications and in-app messaging for web and mobile applications.

7. **Analytics & Performance Monitoring**
– Tracks user interactions and app performance with built-in Google Analytics.
– Helps diagnose slow rendering, network issues, and errors.

8. **Remote Config**
– Allows A/B testing and dynamic updates to app behavior without requiring an update.

9. **Crashlytics**
– Monitors crashes and errors, helping developers identify and fix issues quickly.

### **Why Use Firebase?**
– **No server management:** Serverless infrastructure.
– **Fast development:** Ready-to-use APIs and SDKs.
– **Scalable and secure:** Built on Google Cloud.
– **Cross-platform support:** Works on Android, iOS, and web apps.

Would you like guidance on integrating Firebase with your Laravel or Vue.js project?

User
Create simple portfolio app using firebase as backend vue 3
Assistant
Here’s a simple **portfolio app** using **Vue 3** as the frontend and **Firebase** as the backend for authentication and database storage.

### **Features of the App**
– User Authentication (Signup/Login)
– Add, Edit, Delete Portfolio Projects
– Store portfolio projects in **Firestore**
– Upload images to **Firebase Storage**

## **Step 1: Setup Firebase**
1. Go to [Firebase Console](https://console.firebase.google.com/).
2. Create a new project.
3. Navigate to **Build > Authentication** and enable **Email/Password authentication**.
4. Navigate to **Firestore Database** → Click "Create database" → Select "Start in test mode".
5. Navigate to **Storage** → Click "Get Started" → Choose test mode.
6. Click the **Web** icon (“) to register your app.
7. Copy your **Firebase Config** and keep it for later.

## **Step 2: Setup Vue 3 App**
Run the following command to create a new Vue 3 project with Vite:

yarn create vite vue-portfolio --template vue
cd vue-portfolio
yarn install

## **Step 3: Install Firebase**

yarn add firebase

## **Step 4: Configure Firebase in Vue**
Create a new file **`src/firebase.js`** and add:

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID",
};

const app = initializeApp(firebaseConfig);

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

## **Step 5: Create Authentication (Signup & Login)**
Create **`src/views/Auth.vue`**:

<template>
  <div class="auth-container">
    <h2>{{ isLogin ? "Login" : "Signup" }}</h2>
    <form @submit.prevent="handleAuth">
      <input v-model="email" type="email" placeholder="Email" required />
      <input v-model="password" type="password" placeholder="Password" required />
      <button type="submit">{{ isLogin ? "Login" : "Signup" }}</button>
    </form>
    <p @click="toggleAuth">{{ isLogin ? "Create an account" : "Already have an account?" }}</p>
  </div>
</template>

<script>
import { ref } from "vue";
import { auth } from "@/firebase";
import { createUserWithEmailAndPassword, signInWithEmailAndPassword } from "firebase/auth";

export default {
  setup() {
    const email = ref("");
    const password = ref("");
    const isLogin = ref(true);

    const handleAuth = async () => {
      try {
        if (isLogin.value) {
          await signInWithEmailAndPassword(auth, email.value, password.value);
        } else {
          await createUserWithEmailAndPassword(auth, email.value, password.value);
        }
        alert("Success!");
      } catch (error) {
        alert(error.message);
      }
    };

    const toggleAuth = () => {
      isLogin.value = !isLogin.value;
    };

    return { email, password, isLogin, handleAuth, toggleAuth };
  },
};
</script>

<style scoped>
.auth-container {
  text-align: center;
}
</style>

## **Step 6: CRUD for Portfolio Projects**
Create **`src/views/Portfolio.vue`**:

<template>
  <div>
    <h2>My Portfolio</h2>
    <form @submit.prevent="addProject">
      <input v-model="title" type="text" placeholder="Project Title" required />
      <input v-model="description" type="text" placeholder="Project Description" required />
      <input type="file" @change="handleFileUpload" />
      <button type="submit">Add Project</button>
    </form>

    <ul>
      <li v-for="project in projects" :key="project.id">
        <img :src="project.imageUrl" alt="Project Image" width="100" />
        <h3>{{ project.title }}</h3>
        <p>{{ project.description }}</p>
        <button @click="deleteProject(project.id)">Delete</button>
      </li>
    </ul>
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
import { db, storage } from "@/firebase";
import { collection, addDoc, getDocs, deleteDoc, doc } from "firebase/firestore";
import { ref as storageRef, uploadBytes, getDownloadURL } from "firebase/storage";

export default {
  setup() {
    const projects = ref([]);
    const title = ref("");
    const description = ref("");
    const file = ref(null);

    const fetchProjects = async () => {
      const querySnapshot = await getDocs(collection(db, "projects"));
      projects.value = querySnapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
    };

    const handleFileUpload = (event) => {
      file.value = event.target.files[0];
    };

    const addProject = async () => {
      if (!file.value) return alert("Please select an image");

      const fileRef = storageRef(storage, `projects/${file.value.name}`);
      await uploadBytes(fileRef, file.value);
      const imageUrl = await getDownloadURL(fileRef);

      const docRef = await addDoc(collection(db, "projects"), {
        title: title.value,
        description: description.value,
        imageUrl,
      });

      projects.value.push({ id: docRef.id, title: title.value, description: description.value, imageUrl });
      title.value = "";
      description.value = "";
      file.value = null;
    };

    const deleteProject = async (id) => {
      await deleteDoc(doc(db, "projects", id));
      projects.value = projects.value.filter((project) => project.id !== id);
    };

    onMounted(fetchProjects);

    return { projects, title, description, handleFileUpload, addProject, deleteProject };
  },
};
</script>

<style scoped>
ul {
  list-style-type: none;
}
</style>

## **Step 7: Setup Routing**
Modify **`src/router/index.js`**:

import { createRouter, createWebHistory } from "vue-router";
import Auth from "@/views/Auth.vue";
import Portfolio from "@/views/Portfolio.vue";

const routes = [
  { path: "/", component: Auth },
  { path: "/portfolio", component: Portfolio },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;

## **Step 8: Setup Main App**
Modify **`src/App.vue`**:

<template>
  <router-view></router-view>
</template>

## **Step 9: Run the App**

yarn dev

Now, your **Vue 3 Portfolio App** is up and running with **Firebase authentication, Firestore database, and image storage**.

Would you like to deploy this to Firebase Hosting?

Leave a Comment

Your email address will not be published. Required fields are marked *