In this lab you will learn the fundamentals of Firebase Cloud Firestore development for the web. If you are new to Firebase development or looking for an overview of how to get started, you are in the right place. Read on to learn about the specifics of this lab and areas that you will get hands-on practice with.
The following lab is based on the Firebase Fundamentals YouTube Series:
Deploy the Firebase database rules for the project
firebase deploy --only firestore:rules --project {{{ project_0.project_id | "PROJECT_ID" }}}
Note: The above command will update the Cloud Firestore security rules. If this is the first Cloud Shell API command, you may be required to authorize the command. Select AUTHORIZE when presented with this option.
The Security Rules deploy will be similar to below:
Example Output
=== Deploying to '{{{ project_0.project_id }}}'...
i deploying firestore
i firestore: reading indexes from firestore.indexes.json...
i cloud.firestore: checking firestore.rules for compilation errors...
✔ cloud.firestore: rules file firestore.rules compiled successfully
i firestore: uploading rules firestore.rules...
✔ firestore: released rules firestore.rules to cloud.firestore
✔ Deploy complete!
Project Console: https://console.firebase.google.com/project/{{{ project_0.project_id }}}/overview
The Firestore database can now be accessed by the application. The default security rules setting does not permit read/write access to the database. Ensure the security rules reflect the desired access, to learn more on this subject visit Get started with Cloud Firestore Security Rules | Firebase.
With the database security rules in place, the next step is to configure the environment. Learn more about it in the next section.
Task 2. Configuring the Firebase Environment
Before you can add Firebase to your JavaScript app, you need to create a Firebase project and register your app with that project. When you register your app with Firebase, you'll get a Firebase configuration object that you'll use to connect your app with your Firebase project resources.
Note: Before installing the Firebase packages ensure the host device has a valid Node.js installation.
Set up the environment ready for the Firebase application.
Create a default npm project
npm init -y
Install the Firebase SDK package
npm i firebase
At this point you will have a folder complete with entries for node_modules and package.json. In addition the firebase configuration files:
File
Description
firebase.json
Provides the configuration for the available Firebase components. In our example, auth and ui elements will be contained within this file together with port information.
.firebaserc
Provides the linked project configuration information.
The Firebase environment has now been successfully initialized. Next, learn how to create a Firebase application.
Task 3. Creating a Firebase Application
The following section creates the elements required to perform Firebase Authentication using an email/password combination on the web.
Returns the existing default Firestore instance that is associated with the provided FirebaseApp. If no instance exists, initializes a new instance with default settings.
Firestore
import { initializeFirestore } from ‘firebase/firestore'
Initializes a new instance of Cloud Firestore with the provided settings. Can only be called before any other functions, including getFirestore(). If the custom settings are empty, this function is equivalent to calling getFirestore().
Firestore
import { collection } from ‘firebase/firestore'
Gets a CollectionReference instance that refers to the collection at the specified absolute path..
Firestore
import { doc } from ‘firebase/firestore'
Gets a DocumentReference instance that refers to the document at the specified absolute path.
Make a src folder within the firebase-project
mkdir src
Create a src/index.js file with the following content:
Run the build for the application from the command line
npm run build
Note: The build command will generate a webpack dist folder containing the code to access the Firebase Cloud Function application.
Serve the dist directory on port 8080
python3 -m http.server 8080 --directory dist
Open the Cloud Shell web preview on port 8080
Example Output
Cancel the Cloud Shell web preview (Press CTRL-C)
At this point the backend Firebase project is being referenced. Proceed to the next section to learn how to write information to the database.
Task 5. Writing to a Firestore Document
Update the Cloud Firestore firestore configuration to write information to the database.
To add content to the linked Firebase project, use the getFirestore call. Update the src/index.js code created earlier to write to the project Firestore database.
Edit src/index.js
Add an import statement to src/index.js:
import { getFirestore, doc, setDoc } from 'firebase/firestore'
Add a call to getFirestore in src/index.js after the initializeApp call:
const firestore = getFirestore()
Add a writeFirestoreDemo function to write to the Cloud Firestore database
const firestoreIntroDb = doc(firestore, 'firestoreDemo/lab-demo-0001')
function writeFirestoreDemo() {
const docData = {
title: 'Firebase Fundamentals Demo',
description: 'Getting started with Cloud Firestore',
}
setDoc(firestoreIntroDb, docData)
}
writeFirestoreDemo()
The src/index.js file should look similar to below:
Run the build for the application from the command line
npm run build
Serve the dist directory in the browser on port 8080
python3 -m http.server 8080 --directory dist
Open the Cloud Shell web preview on port 8080
In the Cloud console, select the Firestore menu option to view the Firestore data
Note: It may be necessary to refresh the Firestore page to see the updated database content.
Data is now being written to the Firestore database. The next step is to be able to read information from the database.
Task 6. Reading a Firestore Document
Update the Cloud Firestore firestore configuration to read information from the database.
To access document information from the linked Firebase project, add the getDoc call. Update the src/index.js code created earlier to enable the application to read from the project Firestore database.
Add a function readASingleDocument to read from the Firebase database
async function readASingleDocument() {
const mySnapshot = await getDoc(firestoreIntroDb)
if (mySnapshot.exists()) {
const docData = mySnapshot.data()
const dbJSON = await JSON.stringify(docData)
console.log(`Data: ${dbJSON}`)
const dbOBJ = await JSON.parse(dbJSON)
console.log(`Title: ${dbOBJ.title}`)
titleControl.textContent = "Title: " + dbOBJ.title
descriptionControl.textContent = "Description: " + dbOBJ.description
}
}
readASingleDocument()
Note: Do not forget to comment out the writeFirestoreDemo function. If you are unsure how to do this, take a look at the example solution shown below.
The src/index.js file should look similar to below:
Run the build for the application from the command line
npm run build
Serve the dist directory in the browser on port 8080
python3 -m http.server 8080 --directory dist
Open the Cloud Shell web preview on port 8080
In the application output, the information written to the Firestore database is output using HTML. The title and description fields are shown as defined in the original code.
Feel free to make changes to the code to update the application to include different text using the read and write functions provided.
Congratulations!
In just 30 minutes, you developed a solid understanding of Firebase on the Web and the key features. You learned about installing Firebase Firestore, writing information to the database and reading a document. You are now ready to take more labs.
What's next
Try out other Google Cloud features for yourself. Have a look at our tutorials.
Los labs crean un proyecto de Google Cloud y recursos por un tiempo determinado
.
Los labs tienen un límite de tiempo y no tienen la función de pausa. Si finalizas el lab, deberás reiniciarlo desde el principio.
En la parte superior izquierda de la pantalla, haz clic en Comenzar lab para empezar
Usa la navegación privada
Copia el nombre de usuario y la contraseña proporcionados para el lab
Haz clic en Abrir la consola en modo privado
Accede a la consola
Accede con tus credenciales del lab. Si usas otras credenciales, se generarán errores o se incurrirá en cargos.
Acepta las condiciones y omite la página de recursos de recuperación
No hagas clic en Finalizar lab, a menos que lo hayas terminado o quieras reiniciarlo, ya que se borrará tu trabajo y se quitará el proyecto
Este contenido no está disponible en este momento
Te enviaremos una notificación por correo electrónico cuando esté disponible
¡Genial!
Nos comunicaremos contigo por correo electrónico si está disponible
Un lab a la vez
Confirma para finalizar todos los labs existentes y comenzar este
Usa la navegación privada para ejecutar el lab
Usa una ventana de navegación privada o de Incógnito para ejecutar el lab. Así
evitarás cualquier conflicto entre tu cuenta personal y la cuenta
de estudiante, lo que podría generar cargos adicionales en tu cuenta personal.
In this hands-on lab, you will learn how to develop with the Firebase product suite and Cloud Firestore.
Duración:
3 min de configuración
·
Acceso por 30 min
·
30 min para completar