DEV Community

Cover image for Setting Up a Full-Stack Project with React and Firebase: Authentication, Firestore, Storage, Functions & Vertex AI
Gladiators Battle
Gladiators Battle

Posted on

Setting Up a Full-Stack Project with React and Firebase: Authentication, Firestore, Storage, Functions & Vertex AI

In this article, I’ll walk you through setting up a full-stack project using React for the frontend and Firebase for backend services such as authentication, Firestore, storage, cloud functions, and even Vertex AI to bring in AI-driven features. This combination provides a powerful stack for building dynamic, scalable applications, like Gladiators Battle, where players can experience real-time interactions, data storage, and AI-driven functionality.

  1. Initializing the React Project To get started, we’ll set up a new React project.

Steps:
Create the React app:

npx create-react-app gladiators-battle

Organize the File Structure: Separate components, hooks, services, and assets into directories within the src folder to keep the project organized.

Install Firebase SDK:

npm install firebase

The Firebase SDK provides access to the services we’ll be integrating, like authentication, Firestore, and storage.

  1. Setting Up Firebase for Authentication Firebase Authentication handles secure login, with support for email/password authentication, third-party logins, and more.

Steps:
Enable Authentication in the Firebase Console:

Go to the Firebase Console and navigate to the Authentication section.
Enable the sign-in methods you want to support, like Email/Password.
Configure Authentication in React: In a firebaseService.js file, initialize Firebase:

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

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);

Enter fullscreen mode Exit fullscreen mode

Implement Authentication Flow: Using Firebase Auth hooks, you can implement functions for sign-in, sign-up, and sign-out. A simple example for signing up a new user:

import { createUserWithEmailAndPassword } from "firebase/auth";
import { auth } from "./firebaseService";

const signUp = async (email, password) => {
  try {
    const userCredential = await createUserWithEmailAndPassword(auth, email, password);
    return userCredential.user;
  } catch (error) {
    console.error("Error signing up:", error);
  }
};

Enter fullscreen mode Exit fullscreen mode
  1. Firestore for Real-Time Data Storage Firestore provides a scalable, flexible database for storing player data, game stats, and more.

Steps:
Enable Firestore in Firebase Console:

Go to Firestore Database in the Firebase Console and click Create Database.
Initialize Firestore in the Project: In firebaseService.js, add Firestore initialization:

import { getFirestore } from "firebase/firestore";

export const db = getFirestore(app);

Enter fullscreen mode Exit fullscreen mode

Use Firestore in React: Here’s an example of creating and reading data from Firestore:

import { collection, addDoc, getDocs } from "firebase/firestore";
import { db } from "./firebaseService";

const addPlayerData = async (data) => {
  await addDoc(collection(db, "players"), data);
};

const getPlayerData = async () => {
  const querySnapshot = await getDocs(collection(db, "players"));
  querySnapshot.forEach((doc) => {
    console.log(doc.id, " => ", doc.data());
  });
};

Enter fullscreen mode Exit fullscreen mode
  1. Firebase Storage for Assets Firebase Storage allows us to store user-uploaded content and assets like profile images, game assets, etc.

Steps:
Enable Storage in Firebase Console:

Go to Storage in the Firebase Console, and set up the storage bucket.
Initialize Firebase Storage in the Project: Add Firebase Storage initialization in firebaseService.js:

import { getStorage } from "firebase/storage";

export const storage = getStorage(app);

Enter fullscreen mode Exit fullscreen mode

Implement Storage Functionality: Here’s an example for uploading an image:

import { ref, uploadBytes, getDownloadURL } from "firebase/storage";
import { storage } from "./firebaseService";

const uploadImage = async (file) => {
  const storageRef = ref(storage, `images/${file.name}`);
  await uploadBytes(storageRef, file);
  return getDownloadURL(storageRef);
};

Enter fullscreen mode Exit fullscreen mode
  1. Firebase Functions for Backend Logic Firebase Functions allow you to write and deploy backend logic that responds to HTTP requests, Firestore triggers, and more.

Steps:
Set Up Firebase Functions:

In your project directory, initialize Firebase functions:

firebase init functions

Enter fullscreen mode Exit fullscreen mode

Choose JavaScript or TypeScript as the language and set up Firebase functions.
Create a Cloud Function: Here’s an example of a simple HTTP function:

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

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

Enter fullscreen mode Exit fullscreen mode
const functions = require("firebase-functions");

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

Enter fullscreen mode Exit fullscreen mode

Deploy Functions: Deploy your functions using:

firebase deploy --only functions

Trigger Firestore Functions: You can also set up functions that trigger on Firestore changes:

exports.onPlayerCreate = functions.firestore.document("players/{playerId}")
  .onCreate((snapshot, context) => {
    console.log("New player added:", snapshot.data());
  });

Enter fullscreen mode Exit fullscreen mode
  1. Integrating Vertex AI for Advanced AI Features To add AI-driven features, such as recommendations or natural language processing, Vertex AI provides a suite of tools that integrate seamlessly with Firebase.

Steps:
Enable Vertex AI in Google Cloud Console:

Go to the Google Cloud Console, and enable Vertex AI.
Configure Vertex AI: Set up a machine learning model in Vertex AI, such as a recommendation engine or NLP model.

Access Vertex AI via Firebase Functions: Use Firebase Functions to connect to Vertex AI:

const { PredictionServiceClient } = require("@google-cloud/aiplatform").v1;

exports.recommendCards = functions.https.onCall(async (data, context) => {
  const client = new PredictionServiceClient();
  const request = {
    name: client.modelPath("PROJECT_ID", "LOCATION", "MODEL_ID"),
    instances: [{ content: data.input }],
  };
  const [response] = await client.predict(request);
  return response.predictions;
});

Enter fullscreen mode Exit fullscreen mode

Deploy and Use AI Model: Call this function in your React app to get AI-driven recommendations or other features powered by Vertex AI.

Conclusion
Using React and Firebase alongside Vertex AI has allowed me to create a scalable, dynamic game environment for Gladiators Battle. This setup provides robust backend capabilities and real-time interactions for players, making it ideal for web-based strategy games and complex applications that require seamless integration between front-end and back-end services.

If you’re interested in following along with the development journey, stay tuned for the next article, where I’ll dive into topics such as implementing front-end authentication with Firebase, connecting and communicating effectively with Firestore for data handling, and showcasing some of the gameplay development, including a detailed look at how I built the collectible card game feature.

This ongoing series will provide deep insights into each aspect of game development with React, Firebase, and Vertex AI, focusing on best practices and techniques you can use for your own projects.

🔹 Discover More:

Visit the official game site: https://gladiatorsbattle.com/
Explore the GitHub repository: https://github.com/HanGPIErr/Gladiators-Battle-Documentation
Connect on LinkedIn for updates: https://www.linkedin.com/in/pierre-romain-lopez/
By following this series, you’ll gain valuable insights into setting up a full-stack project with Firebase and learn techniques for enhancing user engagement, boosting real-time capabilities, and even incorporating AI to elevate user experience. Let’s bring the thrill of gladiator battles to life, one development step at a time!

Top comments (0)